Js 数组常用操作
Array
判断数组是否为空
array.length === 0, 条件判断!array.length,转换为 boolArray.isArray(array) && array.length === 0, 先确认是数组再判空
判断是否包含原始值或者对象
引用相等(Reference Equality)
includes, 使用samevaluezero, 返回 boolean
let arr = [1, 2, 3, { a: 1 }, "hello"];
console.log(arr.includes(2)); // true
console.log(arr.includes({ a: 1 })); // false,因为对象引用不同
indexOf(), 使用严格相等===, 返回 boolean
let arr = [1, 2, 3, { a: 1 }, "hello"];
console.log(arr.indexOf(2) !== -1); // true
console.log(arr.indexOf({ a: 1 }) !== -1); // false,因为对象引用不同
值相等(Value Equality)
JSON.stringify(), 将对象转换为 JSON 字符串来比较对象的值,有局限性(如循环引用问题)
let arr = [1, 2, 3, { a: 1 }, "hello"];
let target = { a: 1 };
console.log(
arr.some((element) => JSON.stringify(element) === JSON.stringify(target)),
); // true
isEqualLodash 方法进行深度比较。
let _ = require("lodash");
let arr = [1, 2, 3, { a: 1 }, "hello"];
let target = { a: 1 };
console.log(arr.some((element) => _.isEqual(element, target))); // true
自定义方法
自定义传入的 callback 函数
-
find,传入给定函数,找出数组中第一个符合指定条件的元素。如果找到,则返回该元素;否则返回 undefined -
findIndex,返回的是第一个符合指定条件的元素的索引。如果找到,则返回索引;否则返回 -1 -
filter, 传入给定函数, 返回一个包含符合过滤条件的元素的新数组,若无,返回空数组。 -
some, 传入给定函数, 若至少有一个元素满足指定的条件,返回 true。
数组去重
原始类型
Set
const array = [1, 2, 3, 4, 4, 5, 1];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // [1, 2, 3, 4, 5]
filter&&indexOf
const array = [1, 2, 3, 4, 4, 5, 1];
const uniqueArray = array.filter(
(item, index) => array.indexOf(item) === index,
);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
reduce
const array = [1, 2, 3, 4, 4, 5, 1];
const uniqueArray = array.reduce((acc, item) => {
if (!acc.includes(item)) {
acc.push(item);
}
return acc;
}, []);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
Map
const array = [1, 2, 3, 4, 4, 5, 1];
const map = new Map();
const uniqueArray = array.filter((item) => !map.has(item) && map.set(item, 1));
console.log(uniqueArray); // [1, 2, 3, 4, 5]
_.uniqin Lodash
const _ = require("lodash");
const array = [1, 2, 3, 4, 4, 5, 1];
const uniqueArray = _.uniq(array);
console.log(uniqueArray); // [1, 2, 3, 4, 5]
对象数组
_.uniqBy, in Lodash,转换或提取对应的值后比较
_.uniqBy([2.1, 1.2, 2.3], Math.floor);
// => [2.1, 1.2]
// The `_.property` iteratee shorthand.
_.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], "x");
// => [{ 'x': 1 }, { 'x': 2 }]
_.uniqWith, in Lodash, 额外提供对比方法
var objects = [
{ x: 1, y: 2 },
{ x: 2, y: 1 },
{ x: 1, y: 2 },
];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
- 自定义实现