simonyouth / Blog

Record techniques like javascript
0 stars 0 forks source link

对象数组去重 #3

Open simonyouth opened 5 years ago

simonyouth commented 5 years ago

实现对象数据去重,数组为:

const objArr = [{
  name: 'test', sex: 'female', age: 18,
}, {
  name: 'test', sex: 'female', age: 18,
}]
  uniq = (arr) => {
    const stringArr = arr.map(v => JSON.stringify(v));
    // 利用Set
    const set = new Set(stringArr);
    const res = [];
    set.forEach(v => res.push(JSON.parse(v)));
    return res;
  };
 uniq(objArr); //  [{ name: 'test', sex: 'female', age: 18 }]

先将数组的每一项转化为string,利用Set特性去掉重复值,再将结果转为Object