假設我們有以下字典陣列:
var dictionary_demo = [
[
{country: "georgia", value: sunny},
{country: "france", value: rainy}
],
[
{country: "georgia", value: sunny},
{country: "france", value: gloomy}
],
[
{country: "georgia", value: rainy},
{country: "france", value: dry}
]
]
我將如何獲得告訴我的輸出:
在格魯吉亞:晴天出現 2 次,雨天出現 1 次。
法國:下雨1次,陰天1次,干旱1次
uj5u.com熱心網友回復:
使用陣列陣列(JS 中字典的正確術語是陣列),很容易使用 將flatMap
內部陣列中的所有值提取到外部陣列中。從那里您可以遍歷展平的陣列并收集您想要的值。
對于此示例,我可能使用該array.reduce
方法將生成的平面陣列轉換為具有每個國家/地區的鍵的物件,值是具有每種天氣型別的鍵的另一個物件,以及發生頻率的值。
var dictionary_demo = [
[
{country: "georgia", value: "sunny"},
{country: "france", value: "rainy"}
],
[
{country: "georgia", value: "sunny"},
{country: "france", value: "gloomy"}
],
[
{country: "georgia", value: "rainy"},
{country: "france", value: "dry"}
]
]
function weatherFrequency(arr) {
// flatten the array
const flatArr = arr.flatMap(a => a)
// use flattened array to transform the values into frequencies
const sortedArr = flatArr.reduce((accum, { country, value }) => {
// check if key exists, if not, add it
if (!accum[country]) accum[country] = {}
// check if weather type exists, if so add 1, if not, assign 1
accum[country][value] ? accum[country][value] = 1 : accum[country][value] = 1
// return the accumulator for the next iteraction of `reduce`
return accum
}, {})
return sortedArr
}
// check resulting object from the `reduce` function
console.log(weatherFrequency(dictionary_demo))
// produce a string with the values you want
const countryWeather = weatherFrequency(dictionary_demo)
// use string interpolation to extract values you need
console.log(`in georgia: sunny occurs ${countryWeather.georgia.sunny} times, and rainy occurs ${countryWeather.georgia.rainy} time`)
uj5u.com熱心網友回復:
var dictionary_demo = [
[
{country: "georgia", value: "sunny"},
{country: "france", value: "rainy"}
],
[
{country: "georgia", value: "sunny"},
{country: "france", value: "gloomy"}
],
[
{country: "georgia", value: "rainy"},
{country: "france", value: "dry"}
]
]
var res = dictionary_demo.reduce(function(acc,e){
return acc.concat(e);
},[]).reduce(function(acc, e){
if(!acc[e.country])
acc[e.country] = {[e.value]: 1};
else
acc[e.country][e.value] = (acc[e.country][e.value] || 0) 1;
return acc;
}, {});
console.log(res)
uj5u.com熱心網友回復:
由于這是一個陣列陣列,您可以使用 平展該陣列depth = 2
,然后您可以使用該函式Array.prototype.reduce
來構建所需的輸出。
const arr = [ [ {country: "georgia", value: "sunny"}, {country: "france", value: "rainy"} ], [ {country: "georgia", value: "sunny"}, {country: "france", value: "gloomy"} ], [ {country: "georgia", value: "rainy"}, {country: "france", value: "dry"} ]];
const result = arr.flat(2).reduce((a, {country, value}) => {
const current = (a[country] ?? (a[country] = {[value]: 0}));
a[country][value] = (a[country][value] ?? 0) 1;
return a;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/497770.html
標籤:javascript 数组 排序 字典 频率