簡體   English   中英

返回按數量/長度分組的具有相同值的新對象數組

[英]Return a new array of objects with same values grouped by qauntity/length

所以我目前有一個這樣的數組:

const allMeats = ['Bacon','Bacon','Bacon', 'Steak', 'Lettuce', 'Cabbage','Cabbage','Cabbage','Steak', 'Veal']

我想對數組進行變形,使其成為一個對象數組,其鍵/值確定重復項的值。

目前我有

const meatsGrouped = allMeats.reduce(
    (acum, cur) => Object.assign(acum, { [cur]: (acum[cur] || 0) + 1 }),
    [],
  );

但是這段代碼將數組轉換為: [Bacon: 3, Steak: 2, Lettuce: 1, Cabbage: 3, Veal: 1] ,理想情況下我希望它看起來像這樣: [{Bacon: 3}, {Steak: 2}, {Lettuce: 1}, {Cabbage: 3}, {Veal: 1}]

任何人都可以告訴我我做錯了什么/失蹤了嗎?

您可以使用 reduce 和 map 方法來做到這一點。

 const allMeats = [ 'Bacon', 'Bacon', 'Bacon', 'Steak', 'Lettuce', 'Cabbage', 'Cabbage', 'Cabbage', 'Steak', 'Veal', ]; const ret = Object.entries( allMeats.reduce((prev, c) => { const p = prev; const key = c; p[key] = p[key]?? 0; p[key] += 1; return p; }, {}) ).map(([x, y]) => ({ [x]: y })); console.log(ret);

您可以使用 reduce 方法執行以下操作,

let allMeats = ['Bacon','Bacon','Bacon', 'Steak', 'Lettuce', 'Cabbage','Cabbage','Cabbage','Steak', 'Veal'];
let res = allMeats.reduce((prev, curr) => {
  const index = prev.findIndex(item => item.hasOwnProperty(curr));
  if(index > -1) {
    prev[index][curr]++;
  }else {
    prev.push({[curr]: 1});
  }
  return prev;
}, []);
console.log(res);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM