javascript JS -两个数组之和,其中数组可以不等长

hmtdttj4  于 2023-02-15  发布在  Java
关注(0)|答案(7)|浏览(168)

我需要这样的功能。

function sum(arr1, arr2) {
  return totalArray
};

sum([1,2,3,4], [5,6,7,8,9]) // [6,8,10,12,9]

我是这么试的:

var array1 = [1, 2, 3, 4];
var array2 = [5, 6, 7, 8, 100];
var sum = array1.map((num, idx) => num + array2[idx]); // [6,8,10,12]
ukxgm1gy

ukxgm1gy1#

首先,可以使用Spread syntax (...)从函数的arguments中获取数组,然后使用Array.prototype.sort()按数组的length对其进行排序,最后使用Array.prototype.reduce()获取结果数组
代码:

const sum =(...arrays) => arrays
  .sort((a, b) => b.length - a.length)
  .reduce((a, c) => a.map((n, i) => n + (c[i] || 0)) || c)

// two arrays
const resultTwoArrays = sum([1, 2, 3, 4], [5, 6, 7, 8, 9])
console.log(resultTwoArrays) // [6, 8, 10, 12, 9]

// three arrays or more...
const resultThreeArrays = sum([1, 2, 3, 4], [5, 6, 7, 8, 9], [1, 2])
console.log(resultThreeArrays) // [7, 10, 10, 12, 9]
.as-console-wrapper { max-height: 100% !important; top: 0; }
jvidinwx

jvidinwx2#

冒着由于使用循环而不受欢迎的风险:

function sum(arr1, arr2) {
    let totalArray = [];
    const totalLength =  Math.max(arr1.length, arr2.length);
    for (let i = 0; i < totalLength; i++) {
        totalArray[i] = (arr1[i] || 0) + (arr2[i] || 0);
    }
    return totalArray;
}

|| 0处理数组在i处没有项的可能性,因为如果没有项,arrX[i]的结果是undefinedundefined || 0的结果是0

tpgth1q7

tpgth1q73#

我试着这样。

var array1 = [1, 2, 3, 4];
 var array2 = [5, 6, 7, 8, 100];
 var sum = array1.map((num, idx) => num + array2[idx]); // [6,8,10,12]

非常接近,但是map会在array1的末尾停止,所以你不会从array2中得到后续的条目。只要选择两个数组中较长的一个,然后处理另一个数组在arrayX[idx]处可能没有条目的事实。你可以用|| 0习惯用法来做到这一点:

function sum(array1, array2) {
  var a, b;
  if (array1.length > array2.length) {
    a = array1;
    b = array2;
  } else {
    a = array2;
    b = array1;
  }
  return a.map((num, idx) => num + (b[idx] || 0));
}

console.log(sum([1, 2, 3, 4], [5, 6, 7, 8, 100]));

或者,您可以使用新的(但可进行多边形填充)Array.from来创建结果数组,并使用回调来构建条目:

function sum(array1, array2) {
  return Array.from(
    {length: Math.max(array1.length, array2.length)},
    (_, i) => (array1[i] || 0) + (array2[i] || 0)
  );
}

console.log(sum([1, 2, 3, 4], [5, 6, 7, 8, 100]));

不过,Mosho's answer非常简单。

0md85ypi

0md85ypi4#

根据长度找到长数组和短数组,用Array.map()迭代短数组,从长数组中取值,然后用Array.slice()Array.concat()将长数组剩余的部分相加:

function sum(arr1, arr2) {
  const [l, s] = arr1.length >= arr2.length ? [arr1, arr2] : [arr2, arr1];
    
  return s.map((n, i) => n + l[i])
        .concat(l.slice(s.length));
};

console.log(sum([1,2,3,4], [5,6,7,8,9]));
zbsbpyhn

zbsbpyhn5#

我们在玩代码高尔夫吗?这是个生成器解决方案。

const summer = function*(a, b, i=0) {
  while(i < a.length || i < b.length) yield (a[i] || 0)  + (b[i++] || 0);
};
const sum = (a, b) => [...summer(a,b)];

console.log(sum([1,2,3,4], [5,6,7,8,9])) // [6,8,10,12,9]
liwlm1x9

liwlm1x96#

您可以使用类似以下的自定义逻辑:

function sum(arr1, arr2) {
  var length, selectedArray, nonSelectedArray;
  if(arr1.length>arr2.length){
   length = arr1.length;
   selectedArray = arr2;
   nonSelectedArray = arr1;
  }else {
   length = arr2.length;
   selectedArray = arr1;
   nonSelectedArray = arr2;
  }
  var totalArray = [];
  for(var i=0; i<length; i++){
    if(selectedArray[i]){
      totalArray.push(selectedArray[i] + nonSelectedArray[i]);
    } else {
      totalArray.push(nonSelectedArray[i]);
    }
  }
  return totalArray
};

var res = sum([1,2,3,4], [5,6,7,8,9]);
console.log(res);
k97glaaz

k97glaaz7#

尝试使用map()

function sum(arr1, arr2) {
  var [a1, a2] = arr1.length > arr2.length ? [arr1, arr2] : [arr2, arr1]
  var totalArray = a1.map(function(i, idx){
    i = (i + a2[idx] || i + 0); 
    return i;
  })
  return totalArray;
};

console.log(sum([1,2,3,4], [5,6,7,8,9])) // [6,8,10,12,9]

相关问题