1、将一个大数组分成多个两个元素的小数组:
Array.from()实现:
Array.from({ length: Math.floor(uniqueArr.length / 2) }, (_, i) => [
uniqueArr[i * 2],
uniqueArr[i * 2 + 1],
]);
Array.slice()实现:
const sliceArray=[]
for(let i=0; i<uniqueArr.length; i=i+2){
sliceArray.push(uniqueArr.slice(i,i+2))
}
return sliceArray
2、数组去重
Array.filter()实现:
const newArr=[]
const hash: { [key: string]: boolean } = {}
const uniqueArr = videos.filter(function (item) {
if (!hash[item.id]) {
hash[item.id] = true;
newArr.push(item);
}
return newArr
})
Array.reduce()实现:
const hash: { [key: string]: boolean } = {};
const uniqueArr = videos.reduce((prev, cur) => {
if (!hash[cur.id]) {
hash[cur.id] = true;
prev.push(cur);
}
return prev;
}, []);
|