Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách xóa phần tử cụ thể khỏi mảng trong JavaScript

Viết phương thức Array.prototype.remove() nhận một đối số: callback function hoặc giá trị phần tử. Nếu là function, dùng giá trị trả về của function làm phần tử cần xóa. Tìm và xóa phần tử đó in-place, trả về true nếu xóa thành công, false nếu không tìm thấy.

Ví dụ

const arr = [12, 45, 78, 54, 1, 89, 67];
const names = [
  { fName: 'Aashish', lName: 'Mehta' },
  { fName: 'Vivek', lName: 'Chaurasia' },
  { fName: 'Rahul', lName: 'Dev' }
];

const remove = function(val) {
  let index;
  if (typeof val === 'function') {
    index = this.findIndex(val);
  } else {
    index = this.indexOf(val);
  }
  if (index === -1) {
    return false;
  }
  return !!this.splice(index, 1)[0];
};

Array.prototype.remove = remove;
console.log(arr.remove(54));
console.log(arr);
console.log(names.remove((el) => el.fName === 'Vivek'));
console.log(names);

Kết quả

Đầu ra trong console sẽ là:

true
[ 12, 45, 78, 1, 89, 67 ]
true
[ { fName: 'Aashish', lName: 'Mehta' }, { fName: 'Rahul', lName: 'Dev' } ]