如何检查第二个数组中的第一个数组的值并添加与之关联的值?

时间:2018-06-22 08:50:19

标签: javascript jquery arrays javascript-objects

我有两个带有值的数组。我正在尝试获取desiredArray,它应检查firstArray中的secondArray值,如果匹配,则应添加与它们关联的那些值的数字并将其推入{{1} }。有人可以帮忙吗?

desiredArray

3 个答案:

答案 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];