用es6

时间:2018-03-16 06:23:36

标签: javascript ecmascript-6



const uniqBy = (arr, fn) => {
  let res = []
  const hash = new Set()
  for (let i = 0; i < arr.length; i++) {
    const foo = typeof fn === 'function' ? fn(arr[i]) : arr[i][fn]
    if (!hash.has(foo)) {
      res.push(arr[i])
      hash.add(foo)
    }
  }
  return res
}

console.log(uniqBy([2.1, 1.2, 2.3], Math.floor)) // [2.1, 1.2]
console.log(uniqBy([{
  x: 1
}, {
  x: 2
}, {
  x: 1
}], 'x')) // [{x: 1 },{ x: 2 }]
&#13;
&#13;
&#13;

这是我实现uniqBy的代码,但是代码太多了,我希望用更少的代码获得更好的方法

3 个答案:

答案 0 :(得分:0)

 const uniqBy = (arr, fn, set = new Set) => arr.filter(el => (v => !set.has(v) && set.add(v))(typeof fn === "function" ? fn(el) : el[fn]));

答案 1 :(得分:0)

在使用variables比较keys的唯一性时,

MapSet的合适替代品。

// UniqBy.
const uniqBy = (arr, fn) => [...new Map(arr.reverse().map((x) => [typeof fn === 'function' ? fn(x) : x[fn], x])).values()]

// Proof.
console.log(uniqBy([2.1, 1.2, 2.3], Math.floor)) // [2.1, 1.2]
console.log(uniqBy([{x: 1}, {x: 2}, {x: 1}], 'x')) // [{x: 1},{x: 2}]

答案 2 :(得分:0)

这是我对它的看法

const uniqBy = (arr, fn, obj={}) => ((arr.reverse().forEach(item => obj[typeof fn === 'function' ? fn(item) : item[fn]] = item)), Object.values(obj))

console.log(uniqBy([2.1, 2.3, 3.2], Math.floor))
console.log(uniqBy([{x:1}, {x:2}, {x:1}, {x:4}], 'x'))