使用map和reduce来获取对象数组

时间:2016-08-01 22:15:44

标签: javascript functional-programming ecmascript-6

我有一个

阵列
var c = [{name: 'John'}, {name: 'John'}, {name: 'Tom'}];

我想使用reduce方法和map来获得以下结果:

result = [
    { name: "John", occurence: 2 },
    { name: "Tom", occurence: 1 }
  ]

这是我尝试但未完全获得它的尝试。 https://jsfiddle.net/joeSaad/up3ddfzz/



c = [{
  name: 'John'
}, {
  name: 'John'
}, {
  name: 'Simon'
}];

var d = c.reduce((countMap, word) => {
  countMap[word.name] = ++countMap[word.name] || 1;
  return countMap
}, []);

var e = c.reduce((countMap, word) => {
  q = [];
  countMap[word.name] = ++countMap[word.name] || 1;
  var p = {
    name: word.name,
    occurence: countMap[word.name]
  }
  q.push(p);
  return q
}, []);

console.log(e);




非常感谢。提前致谢

1 个答案:

答案 0 :(得分:3)

你肯定在使用reduce的正确轨道上,但我会将计算分成两个不同的步骤

let c = [{name: 'John'}, {name: 'John'}, {name: 'Tom'}];

const pairs = o=> Object.keys(o).map(k=> [k, o[k]])

let count = c.reduce((acc, {name}) => {
  if (acc[name] === undefined)
    return Object.assign(acc, { [name]: 1 })
  else
    return Object.assign(acc, { [name]: acc[name] + 1 })
}, {})

var result = pairs(count).map(([name, occurences]) => ({name, occurences}))

console.log(result)
//=> [ { name: 'John', occurences: 2 }, { name: 'Tom', occurences: 1 } ]

您可以将这些行为抽象为不同的函数,例如

// convert an object to [[key,value]] pairs
const pairs = o=> Object.keys(o).map(k=> [k, o[k]])

// count unique instances of a property value in an array of objects
const countBy = (prop, xs)=> {
  return xs.reduce((acc, x)=> {
    let y = x[prop]
    if (acc[y] === undefined)
      return Object.assign(acc, { [y]: 1 })
    else
      return Object.assign(acc, { [y]: acc[y] + 1 })
  }, {})
}

// your data
let c = [{name: 'John'}, {name: 'John'}, {name: 'Tom'}]

// then chain it all together
let result = pairs(countBy('name', c)).map(([name, occurences]) => ({name, occurences}))

console.log(result)
//=> [ { name: 'John', occurences: 2 }, { name: 'Tom', occurences: 1 } ]

ES6还提供Map,这对于进行这种计算非常有用。

这段代码对我来说读起来更好一些,并且在语义上更正确一些。我们之前的代码完全相同,只是使用了普通对象。 Map是专为此key->value数据设计的数据结构,因此可以使Map成为更好的选择。

唯一的问题是,如果你的代码库还没有以某种方式使用地图,那么为此引入它可能是错误的举动。

// convert a Map to an array of pairs
const mpairs = m=> [...m.entries()]

// countBy this time uses Map
const countBy = (prop, xs)=> {
  return xs.reduce((m, x)=> {
    let y = x[prop]
    if (m.has(y))
      return m.set(y, m.get(y) + 1)
    else
      return m.set(y, 1)
  }, new Map)
}

// your data
let c = [{name: 'John'}, {name: 'John'}, {name: 'Tom'}]

// then chain it all together
let result = mpairs(countBy('name', c)).map(([name, occurences]) => ({name, occurences}))

console.log(result)
//=> [ { name: 'John', occurences: 2 }, { name: 'Tom', occurences: 1 } ]