数组操作方法

15 阅读1分钟

数组(普通数组)去重

  • Array.from(new Set(arr))
  • console.log(Array.from(new Set([1, 2, 3, 3, 4, 4]))) //[1,2,3,4]
  • console.log([...new Set([1, 2, 3, 3, 4, 4])]) //[1,2,3,4]

- 数组(数组对象)去重

 { name: 'name1', id: 1 },
 { name: 'name2', id: 2 }, 
 { name: 'name3', id: 3 }, 
 { name: 'name1', id: 1 }, 
 { name: 'name4', id: 4 }, 
 { name: 'name5', id: 5 }
 ];
 const result = [];
 arr.forEach(item=>{
 // 思想:JSON.stringify()把类型转为string方便比较,如果result中没有,则push
    !result.some(v => JSON.stringify(v) === JSON.stringify(item)) && result.push(item);
 })
 console.log(result) //[{ name: 'name1', id: 1 },{ name: 'name2', id: 2 },{ name: 'name3', id: 3 },{ name: 'name4', id: 4 },{ name: 'name5', id: 5 }]

reduce

reduce(callback,initValue): 函数累加器。 第一个参数callback是操作函数,有四个参数,分别是:初始值(或上一次回调函数的返回值),当前元素值,当前索引,调用reduce数组本身。 callback (pre,current,index,arr)

1、pre (第一次是提供的初始值,往后是上一次调用回调返回的值)
2、current(数组中当前被处理的元素)
3index (当前元素在数组中的索引)
4、arr (调用 reduce 的数组)

第二个参数是初始值。

initialValue (作为第一次调用 callback 的第一个参数。)

let arr=[1,2,3,4,5];
let sum= arr.reduce((pre,current,index,arr)=>{
	console.log(pre,current);
	return pre+current;
},0)
console.log(sum) // sum:15

本文 参考链接 为了做学习记录