将数组中的值与第二个数组javascript中的内容匹配

时间:2020-11-10 11:45:46

标签: javascript arrays functional-programming tuples array.prototype.map

我遇到以下问题:

我想知道第一个数组中位置的平均值,假设在这种情况下为3。3,那么它将是我在第二个数组中寻找的位置,因此将返回“ d”作为答案。这是我的代码,到目前为止,我什至无法返回头寸的总和。你们可以帮我吗?!

const avgPosition = (list1, list2) => {
  return (list1).reduce((a, b) => a + b, 0).map((element,index)=>{
    return [list2[element]]
  })
}

console.log(avgPosition(["a","b","c"],["a","b","c","d","e"]))

1 个答案:

答案 0 :(得分:0)

您想做这样的事情吗?我不确定我是否很好地理解了您的问题,但是我还是尝试了

const avgPosition = (list1, list2) => {
  if(!list1.length) return "I'm sorry I have nothing to do with an empty array!";
  let index = list1.reduce(function(a, b, c) {
    return a + c;
  }, 0) / list1.length;
  return list2[index] || `I'm confused should I pick ${list2[Math.floor(index)]} or ${list2[Math.ceil(index)]}`;
}

console.log(avgPosition([],["a","b","c","d","e"]));
console.log(avgPosition(["a","b","c"],["a","b","c","d","e"]));
console.log(avgPosition(["a","b","c","d"],["a","b","c","d","e"]));