es6数组/数组对象取并集、交集、差集

467 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

数组

1:合并数组(并集)

let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
let arr = Array.from(new Set([...a, ...b]));
console.log('arr',arr);

2:数组相等值(交集)

let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
let arr = Array.from(new Set([...b].filter(x => a.has(x))));

3:数组不等值(差集)

let a=new Set([1,2,3,4,5]);
let b=new Set([1,2,3,4,5,6,7,8,9]);
let arr = Array.from(new Set([...b].filter(x => !a.has(x))));
console.log('arr',arr);

4:二维数组转为一维数组

const arr=[[1,2,3],[3,4],[5]];
 
console.log([].concat.apply([],arr));

数组对象

1:数组对象相等(交集)

let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234}];
let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];
let arr = [...b].filter(x => [...a].some(y => y.id === x.id));
console.log('arr',arr)

2:数组对象不等(差集)

let a=[{id:1,a:123,b:1234},{id:2,a:123,b:1234}];
let b=[{id:1,a:123,b:1234},{id:2,a:123,b:1234},{id:3,a:123,b:1234},{id:4,a:123,b:1234}];
let arr = [...b].filter(x => [...a].every(y => y.id !== x.id));
console.log('arr',arr);

**

两个数组,合并成数组对象

** 例: let arr1= [ "2008-01", "2008-02", "2008-03",..ect ]; let arr2 = [ 0, 0.555,0.293,..ect ] 实现效果: let result = [ {data: 0, date: "2008-01"}, {data: 0.555, date: "2008-02"}, {data: 0.293, date: "2008-03"},..ect ];

方法 一:ES6中的map

 let result = arr1.map((date,i) => ({date, data: arr2[i]}));

方法 二 :ES6+递归

 const zip = ([x,...xs], [y,...ys]) => {
   if (x === undefined || y === undefined)
    return [];
   else
     return [[x,y], ...zip(xs, ys)];
 }
 let result = zip(metrodates, figures).map(([date, data]) => ({date, data}));