计算对象属性的重复数组以产生一个新数组

时间:2019-04-02 07:47:55

标签: javascript arrays reactjs object ecmascript-6

我有这个对象数组

[{
    tag: 'james'
  },
  {
    tag: 'james'
  },
  {
    tag: 'john'
  }
]

我如何计算并产生如下所示的新数组?

[{
  tag: 'james',
  count: 2
}, {
  tag: 'john',
  count: 1
}]

我尝试使用减少产生的对象而不是对象数组。

const arr = [{tag: 'james'},{tag: 'james'},{tag: 'john'}];
let newArr = arr.reduce((accum, arr) => {
  accum[arr.tag] = ++accum[arr.tag] || 1
  return accum
}, {})

console.log(newArr)

6 个答案:

答案 0 :(得分:3)

创建一个对象而不是数字,最后使用Object.values方法从对象中获取这些值。

// just extract values from the object as an array
let res = Object.values(arr.reduce((accum, o) => {
  // initialize object if not defined already
  accum[o.tag] = accum[o.tag] || { ...o, count: 0  }
  // increment count property
  accum[o.tag].count++;
  return accum
}, {}))

let arr = [{tag: 'james'},{tag: 'james'},{tag: 'john'}]

let res = Object.values(arr.reduce((accum, o) => {
  accum[o.tag] = accum[o.tag] || { ...o, count: 0 }
  accum[o.tag].count++;
  return accum
}, {}))

console.log(res)


您甚至可以通过使用附加变量来直接创建数组,以进行对象/索引引用。

// an object for keeping reference 
let ref = {};

let res = arr.reduce((accum, o) => {
  // check reference already defined, if not define refernece and push to the array
  ref[o.tag] || accum.push(ref[o.tag] = { ...o, count: 0 })
  // update count using the refernece keeped in the object
  ref[o.tag].count++;
  return accum
}, []);

let arr = [{tag: 'james'},{tag: 'james'},{tag: 'john'}]

let ref = {};

let res = arr.reduce((accum, o) => {
  ref[o.tag] || accum.push(ref[o.tag] = { ...o, count: 0 })
  ref[o.tag].count++;
  return accum
}, []);

console.log(res)

答案 1 :(得分:2)

您快到了,但是您需要从对象中取出键和值并构建一个新数组。

var array = [{ tag: 'jane' }, { tag: 'jane' }, { tag: 'john' }],
    result = Object
        .entries(
            array.reduce((accum, { tag }) => {
                accum[tag] = (accum[tag] || 0) + 1;
                return accum;
            }, {}))
        .map(([tag, count]) => ({ tag, count }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

首先测试对象是否不存在-​​如果不存在,则创建一个。然后添加到累加器中。另请注意,您需要一个数组,因此对累加器值使用[]而不是{}

const data = [{
    tag: 'james'
  },
  {
    tag: 'james'
  },
  {
    tag: 'john'
  }
];

const grouped = data.reduce((acc, { tag }) => {
  if (!acc.some(e => e.tag == tag)) {
    acc.push({ tag, count: 0 });
  }
  acc.find(e => e.tag == tag).count++;
  return acc;
}, []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: auto; }

答案 3 :(得分:0)

一个简单的代码是:

const arr = [{
    tag: 'james'
  },
  {
    tag: 'james'
  },
  {
    tag: 'john'
  },
  {
    tag: 'lewis'
  },
  {
    tag: 'john'
  }
]

const counts = arr.reduce((acc, cv) => {
  const val = acc.find(t => t.tag == cv.tag)
  if (val) {
    val.count++
    acc.push(val)
    return acc
  }
  cv.count = 1
  acc.push(cv)
  return acc
}, [])

console.log(counts)

答案 4 :(得分:0)

你的直觉很好,你也很亲密;我向您建议一些通用的答案

const groupTags = data => field => Object.values(data.reduce((acc, o) =>
({...acc,
  [o[field]]: {
    [field]: o[field],
    count: acc[o[field]] ? acc[o[field]].count + 1 : 1 
  }
}), {}))

您可以像使用它

groupTags(data)("tag")

答案 5 :(得分:0)

//simple approach using forEach method

let lists = [{tag: 'james'},{tag: 'james'},{tag: 'john'}]; 
const finalOutput = [];
const tempStore = {};

lists.forEach((list) => {
      tempStore[list.tag] = (tempStore[list.tag] == undefined) ? 1: tempStore[list.tag]+1;
      const index = finalOutput.findIndex(e => e.tag == list.tag);
      if(index > -1) {
        finalOutput[index] = {tag: list.tag, count: tempStore[list.tag]}
      }
      else 
        finalOutput.push({tag: list.tag, count: tempStore[list.tag]})
});

console.log(finalOutput);