![](/img/trans.png)
[英]Combine two array into one while getting the sum of instances in second array
[英]Sum the second parameter of an array
我有一個對象,我需要將其累加到單詞出現的次數。 前任:
{
step1: ["luiz"]
step2: ["pedro"]
step3: ["luiz"]
step4: ["luiz"]
step5: ["luiz"]
}
我嘗試使用 .map、.forEach、.filter,但它們都返回未定義。
。篩選
let irmas = answers.filter((answer) => answer[1] === 'luiz)
。地圖
let contagemRespostas = answers.map(function(answer, index) {
return contagemRespostas.index
})
如何僅獲取名稱並添加值?
編輯:
回報是這樣的:
{ 'luiz': 3, 'pedro': 2 }
或最高值{ 'luiz': 3 }
您可以使用 reduce 來創建具有值的對象
const data = { step1: ["luiz"], step2: ["pedro"], step3: ["luiz"], step4: ["luiz"], step5: ["luiz"], } const result = Object.values(data).flat().reduce((acc, cur) => { acc.hasOwnProperty(cur) ? acc[cur]++ : acc[cur] = 1 return acc }, {}) console.log(result) // {luiz: 4, pedro: 1}
嘗試這樣的事情:
https://jsfiddle.net/bwmfhqev/2/
var foo = {
step1: ["luiz"],
step2: ["pedro"],
step3: ["luiz"],
step4: ["luiz"],
step5: ["luiz"]
}
let result = {};
console.log(Object.keys(foo));
// loop over the keys of the object
for(var key of Object.keys(foo)) {
// get the number of occurrences of words in the array for each key
let count= foo[key].reduce((a,c)=> (a[c]=++a[c]||1,a) ,{});
//combine everything into 1 object
for(var key2 of Object.keys(count)) {
console.log(count[key2]);
if(key2 in result) {
result[key2] = result[key2] + count[key2];
}
else {
result[key2] = count[key2];
}
}
}
console.log(result);
這里的想法是處理原始對象中的每個鍵。 然后從每個對象中創建一個對象,獲取每個鍵的每個單詞的出現次數。 然后將它們全部組合成 1 個對象
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.