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

Phương thức _without() trong Underscore/Lodash JavaScript

_.without(array, ...values) (Underscore/Lodash) trả về mảng mới loại bỏ tất cả giá trị xuất hiện trong danh sách values. So sánh bằng === (strict equality), case-sensitive.

Cú pháp

_.without(array, ...valuesToRemove);

Ví dụ cơ bản

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>
  const result = _.without([5, 6, 4, 8, 9, 9, 0, 1], 0, 9, 1);
  document.write(result); // 5,6,4,8
</script>

Case-sensitive

_.without([5, 6, 'c++', 'php', 'java', 'javascript', 0, 1], 0, 'JAVA', 1);
// [5, 6, 'c++', 'php', 'java', 'javascript'] — 'JAVA' ≠ 'java' → không xóa

So sánh với các phương pháp native

1. filter + includes (Native ES7+)

const arr = [5, 6, 4, 8, 9, 9, 0, 1];
const toRemove = [0, 9, 1];
const result = arr.filter(x => !toRemove.includes(x));
// [5, 6, 4, 8] — tương tự _.without

2. filter + Set (Hiệu suất O(n) cho mảng lớn)

const toRemoveSet = new Set([0, 9, 1]);
const result = arr.filter(x => !toRemoveSet.has(x));
// O(n) vs O(n*m) của includes

Bảng so sánh

Phương phápCú phápHiệu suấtDependencyCase-sensitive
_.without_.without(arr, ...vals)O(n*m)Lodash/UnderscoreCó
filter + includesarr.filter(x => !vals.includes(x))O(n*m)Không (native)Có
filter + Setarr.filter(x => !set.has(x))O(n)Không (native)Có
_.difference_.difference(arr, vals)O(n*m)LodashCó

Lưu ý

  • _.without trả về mảng mới — không mutate gốc.
  • So sánh strict equality (===) — object/array khác reference không bị xóa.
  • Lodash cũng có _.difference (nhận array valuesToRemove thay vì variadic args).
  • Nếu không muốn dependency: dùng filter + Set — native, nhanh, ngắn.