簡體   English   中英

轉換嵌套對象數組中的對象

[英]Convert objects in nested array of objects

我有一個看起來像這樣的數據結構:

[
  [
    { word: "china", count: 0 },
    { word: "kids", count: 1 },
    { word: "music", count: 0 },
  ],
  [
    { word: "china", count: 3 },
    { word: "kids", count: 0 },
    { word: "music", count: 2 },
  ],
  [
    { word: "china", count: 10 },
    { word: "kids", count: 3 },
    { word: "music", count: 2 },
  ]
];

我想計算嵌套數組中屬性詞的每個值的最小和最大計數數。

例如,單詞“china”的最大計數為 10,最小計數為 0。

我想完成這樣的事情:

{ word: "china", min: 0, max: 10 }

我該怎么做呢?

有很多方法可以解決這個問題。 如果您首先將數據轉換為 object,其鍵是單詞,其值是每個單詞的計數,那么您可以對計數執行任意數量的操作(不僅僅是查找最小值和最大值):

 function transform (array) { const counts = {}; for (const {count, word} of array.flat()) { (counts[word]??= []).push(count); } return counts; } const input = [ [ { word: "china", count: 0 }, { word: "kids", count: 1 }, { word: "music", count: 0 }, ], [ { word: "china", count: 3 }, { word: "kids", count: 0 }, { word: "music", count: 2 }, ], [ { word: "china", count: 10 }, { word: "kids", count: 3 }, { word: "music", count: 2 }, ], ]; const transformed = transform(input); console.log(transformed); //=> { china: [ 0, 3, 10 ], kids: [ 1, 0, 3 ], music: [ 0, 2, 2 ] } for (const [word, counts] of Object.entries(transformed)) { const sorted = [...counts].sort((a, b) => a - b); console.log({ word, min: sorted.at(0), max: sorted.at(-1), }); } //=> // { word: "china", min: 0, max: 10 } // { word: "kids", min: 0, max: 3 } // { word: "music", min: 0, max: 2 }

參考:

您可以使用Array#reduce在遍歷數組時收集給定單詞的最小值和最大值。

 let arr=[[{word:"china",count:0},{word:"kids",count:1},{word:"music",count:0},],[{word:"china",count:3},{word:"kids",count:0},{word:"music",count:2},],[{word:"china",count:10},{word:"kids",count:3},{word:"music",count:2},]]; const getStats = (arr, w) => arr.flat().reduce((acc, {word, count})=>{ if (w === word) acc.min = Math.min(acc.min, count), acc.max = Math.max(acc.max, count); return acc; }, { word: w, min: Infinity, max: -Infinity}); console.log(getStats(arr, 'china'));

暫無
暫無

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

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