JavaScript 数组 - 跨键添加值,但有例外

JavaScript arrays - adding values across keys with exceptions

我正在尝试获取数组中的所有条目并将它们组合成一个数组。

这是一个例子:

x = "x"
var oldArray = [
    [2,2,1,2,2,x,2,2,2,x,2,2,1],
    [1,2,x,2,2,x,2,1,2,x,2,2,x]
];

我想要实现的是一个如下所示的新数组:

var newArray = 
    [3,4,x,4,4,x,4,3,4,x,4,4,x];

字符x就像一个标志,忽略添加。如果任一值中有 x,则新值将只是 x.

每个子数组的长度始终相同,但可能有两个以上的子数组。

使用array.reduce() to return an array of the added values, iterating over each sub-array and returning the resulting array (the accumulator argument). Inside the callback to passed to reduce(), use array.forEach()遍历sub-array中的每个元素。

var newArray = oldArray.reduce(function(accumulator, subArray, subArrayIndex) {
    //process each sub-array
    subArray.forEach(function(value, index) {
        //process each element in the sub-array
    });
    //return accumulator after processing the sub-array (at subArrayIndex)
}, []);

此技术比已接受的答案有优势,包括不必担心手动增加迭代器索引、限制循环条件(例如 for(var j=0; j < array.length; j++) )等。有关更多阅读功能技术优势的信息reduce()、map() 等。参见 functional programming in JavaScript。我推荐练习。

x = "x"
var oldArray = [
  [2, 2, 1, 2, 2, x, 2, 2, 2, x, 2, 2, 1],
  [1, 2, x, 2, 2, x, 2, 1, 2, x, 2, 2, x]
];
var newArray = oldArray.reduce(function(accumulator, subArray, subArrayIndex) {
  subArray.forEach(function(value, index) {
    if (value == x) {
      accumulator[index] = x; //make newArray[index] an x
    } else if (accumulator[index] !== x) { //don't add to an x
      accumulator[index] = value + (accumulator[index] ? accumulator[index] : 0); //add the value from the current sub-array
    }
  });
  return accumulator;
}, []); //the array (2nd argument) is the initial value for the accumulator
console.log('newArray: ', newArray);

编辑:

基于 this test on jsperf.com,此答案中的代码片段比接受的答案

x = "x"
var oldArray = [
  [2, 2, 1, 2, 2, x, 2, 2, 2, x, 2, 2, 1],
  [1, 2, x, 2, 2, x, 2, 1, 2, x, 2, 2, x]
];

var result = oldArray.reduce(function(res, sub) { // for each sub
  for(var i = 0; i < sub.length; i++) { // for each item in sub
    if(sub[i] == x) res[i] = x; // if this item sub[i] is x then make res[i] == x 
    else if(res[i] != x) res[i] = (res[i] || 0) + sub[i]; // if not and if res[i] is not already set to x then add sub[i] to res[i] and store it back into res[i] (if res[i] is not yet defined add 0 instead)
  }
  return res; // return the accumulator (see the docs for Array.prototype.reduce)
}, []); // start with an empty array as the accumulator res (see the docs)

console.log(result);

很简单。这适用于两个维度中的任意数量的事物。

x = "x"
var oldArray = [
    [2,2,1,2,2,x,2,2,2,x,2,2,1],
    [1,2,x,2,2,x,2,1,2,x,2,2,x]
];
newArray = []
for(i=0;i<oldArray.length;i++){
    for(j=0;j<oldArray[i].length;j++){
        if(oldArray[i][j] == x || newArray[j] == x)
            newArray[j] = x;
        else{
            if( i == 0 )
                newArray[j] = oldArray[i][j];
            else
                newArray += oldArray[i][j];            
        }
    }
}

你可以这样做:

var x = "x"
var max_x = max_y = 0;
var newArray = [];
var oval = nval = null;

var oldArray = [
    [2,2,1,2,2,x,2,2,2,x,2,2,1],
    [1,2,x,2,2,x,2,1,2,x,2,2,x]
];

max_x = oldArray[0].length;
max_y = oldArray.length;

for(var n1= 0; n1<max_x; n1++) {
  nval = 0;
  for(var n0=0; n0<max_y; n0++) {
    oval = oldArray[n0][n1];
      if(oval === x) {
        nval = oval;
        break;
       }
    nval += oval;
  }
  newArray.push(nval);
}

console.log(newArray);

您可以使用嵌套的 for..of 循环,Array.prototype.entries()

const x = "x";

let oldArray = [
    [2,2,1,2,2,x,2,2,2,x,2,2,1],
    [1,2,x,2,2,x,2,1,2,x,2,2,x]
];

let res = [];

for (let arr of oldArray) {
  for (let [key,  value] of arr.entries()) {
    if (res[key] !== x) res[key] = value === x ? x : (res[key] || 0) + value;
  }
}

console.log(res);

Blahh Blahh 我找到了最简单的解决方案:)

<html>

    <script>
    x = "x";
    var oldArray = [
        [2,2,1,2,2,x,2,2,2,x,2,2,1],
        [1,2,x,2,2,x,2,1,2,x,2,2,x]
    ];
    var newArray = [];

    var u ;
    var length = oldArray[0].length;

    for(var i = 0 ; i< length  ; i++ )

    {
    alert(oldArray[0][i]+" "+oldArray[1][i]);
        if(oldArray[0][i]!= x &&  oldArray[1][i] != x){
            u = oldArray[0][i]+oldArray[1][i];
            newArray.push(u);
            }
            else if(oldArray[0][i]== x){
            newArray.push(x);
            }
            else if (oldArray[1][i] == x) {
            newArray.push(x);
            }

    }
    console.log(newArray);
    </script>