我有两个带有值的数组。我正在尝试获取desiredArray
,它应检查firstArray
中的secondArray
值,如果匹配,则应添加与它们关联的那些值的数字并将其推入{{1} }。有人可以帮忙吗?
desiredArray
答案 0 :(得分:0)
您可以使用Array.reduce()
:
firstArray=["Jack Sparrow", "Ryan Gosling", "Peter Parker", "Mark Waugh", "Steve Jobs"];
secondArray=["Jack Sparrow :10", "Ryan Gosling :40", "Peter Parker :30", "Mark Warner: 40", "Shane Warne :30", "Steve Jobs : 20", "Tony Stark :90", "Adam Gilchrist: 45.5"];
var result = firstArray.reduce((a,curr)=>{
var str = secondArray.find((b)=>b.includes(curr));
if(str){
a += Number(str.split(":")[1]);
}
return a;
},0);
console.log(result);
答案 1 :(得分:0)
您可以使用2 reduce
。第一个reduce
是从secondArray
创建一个临时对象。使用名称作为键,使用数字作为值。这将使检查名称是否存在变得更加容易。无需遍历secondArray
的每个循环firstArray
第二个reduce
是通过firstArray
循环并求和。
var firstArray = ["Jack Sparrow", "Ryan Gosling", "Peter Parker", "Mark Waugh", "Steve Jobs"]
var secondArray = ["Jack Sparrow :10", "Ryan Gosling :40", "Peter Parker :30", "Mark Warner: 40", "Shane Warne :30", "Steve Jobs : 20", "Tony Stark :90", "Adam Gilchrist: 45.5"];
var tempObject = secondArray.reduce((c, v) => {
let [k, o] = v.split(':');
c[k.trim()] = +o;
return c;
}, {});
var desiredArray = [firstArray.reduce((c, v) => c + (tempObject[v] || 0), 0)];
console.log(desiredArray);
答案 2 :(得分:0)
尝试
let count = 0;
secondArray.forEach(item => {
let data = item.split(":");
let key = data[0];
let value = data[1];
if(key in firstArray){
count += value;
}
})
let desiredArray = [count];