1.去除传入的数组值一样的原数组数据
function removeMatchingValues(arr1, arr2) {
return arr1.filter(value => !arr2.includes(value));
}
// 示例用法
const array1 = ['apple', 'banana', 'orange', 'grape'];
const array2 = ['banana', 'orange'];
const result = removeMatchingValues(array1, array2);
console.log(result); // 输出: ['apple', 'grape']
2.不重复添加
function addUniqueValues(arr1, arr2) {
arr2.forEach(value => {
if (!arr1.includes(value)) {
arr1.push(value); // 如果 arr1 不包含该值,则添加
}
});
return arr1;
}
// 示例用法
const array1 = ['apple', 'banana'];
const array2 = ['banana', 'orange', 'grape'];
const result = addUniqueValues(array1, array2);
console.log(result); // 输出: ['apple', 'banana', 'orange', 'grape']
3.分组
const items = [
{ id: 1, name: 'item1', category: 'food' },
{ id: 2, name: 'item2', category: 'drink' },
{ id: 3, name: 'item3', category: 'food' },
{ id: 4, name: 'item4', category: 'drink' },
{ id: 5, name: 'item5', category: 'clothes' }
];
// 使用reduce进行分组
const groupedItems = items.reduce((accumulator, item) => {
// 使用item的category作为key
const key = item.category;
// 如果accumulator中还没有这个key,则创建一个新的数组
if (!accumulator[key]) {
accumulator[key] = [];
}
// 把当前item添加到对应的数组中
accumulator[key].push(item);
return accumulator;
}, {});
console.log(groupedItems);
//这段代码执行后,groupedItems将会是一个对象,其中的键是category,值是包含对应类别的所有项目的数组:
{
food: [{ id: 1, name: 'item1', category: 'food' }, { id: 3, name: 'item3', category: 'food' }],
drink: [{ id: 2, name: 'item2', category: 'drink' }, { id: 4, name: 'item4', category: 'drink' }],
clothes: [{ id: 5, name: 'item5', category: 'clothes' }]
}
4.去重
方法一:使用 Set 和 Spread Operator
const array = [1, 2, 2, 3, 4, 4, 5, 1];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
方法二:使用 Array.filter
如果你不想使用 Set
或者需要兼容旧的浏览器版本(不支持ES6),可以使用 filter
方法配合 indexOf
:
const uniqueArray = array.filter((value, index, self) => {
return self.indexOf(value) === index;
});
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
方法三:使用 Array.reduce
使用 reduce
函数可以构建一个新数组,同时检查当前元素是否已存在于结果数组中:
const uniqueArray = array.reduce((acc, value) => {
if (!acc.includes(value)) {
acc.push(value);
}
return acc;
}, []);
console.log(uniqueArray); // 输出: [1, 2, 3, 4, 5]
方法四:使用 Map
如果数组中的元素是对象或复杂类型,可以使用 Map
来跟踪已存在的元素:
const objects = [{ id: 1 }, { id: 2 }, { id: 1 }, { id: 3 }];
const uniqueObjects = array.reduce((acc, obj) => {
if (!acc.has(obj.id)) {
acc.set(obj.id, obj);
}
return acc;
}, new Map()).values();
console.log([...uniqueObjects]); // 输出: [{ id: 1 }, { id: 2 }, { id: 3 }]