[英]Find objects with same property value and add them in new array property
[英]Map through array of objects and add counter of elements with the same property value
給定以下數組:
const arr = [
{color: 'red'},
{color: 'red'},
{color: 'green'},
{color: 'blue'},
{color: 'blue'},
{color: 'red'}]
如何通過其元素 map 創建一個對象數組,該數組使用屬性colorIndex
擴展,該數組將用作之前有多少元素具有相同color
屬性的計數器?
結果將是以下數組:
[
{color: 'red', colorIndex: 0},
{color: 'red', colorIndex: 1},
{color: 'green', colorIndex: 0},
{color: 'blue', colorIndex: 0},
{color: 'blue', colorIndex: 1},
{color: 'red', colorIndex: 2}
]
是否有一些優雅的解決方案來實現這一目標?
我想到的第一個解決方案並不優雅,但它可以解決問題。 最好使用額外的 object。
const foundItems = {};
arr.map(item => {
let foundItem = foundItems[item.color] ? foundItems[item.color]+ 1 : 0;
foundItems[item.color] = founditem;
return {
...item,
colorIndex: foundItem,
}
})
好吧,不知道你為什么要問,你已經嘗試過什么來解決這個問題。 在根本沒有上下文的情況下很難得到正確的答案。 但這是我的方法,也許你會學到一點:
arr.map((elem, index) => {
// we only care about values before current index, to see how many elements with given color were **before**
var colors = arr.map((obj) => obj.color).splice(0, index + 1);
return {
...elem, // using spread operator to get all properties of original object
count: colors.reduce(
(prev, curr) => (curr == elem.color ? prev + 1 : prev),
-1 // starting from -1 to get 0-based counter
),
};
})
在此處的 stackblitz 上查看: https://stackblitz.com/edit/js-bnru4m
閱讀有關減少的更多信息: https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
閱讀有關擴展運算符的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
閱讀有關拼接數組的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
閱讀有關映射數組的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.