JavaScript数组 - 在具有异常的键上添加值

时间:2017-02-09 00:31:37

标签: javascript arrays loops addition

我试图获取数组中的所有条目并将它们组合成一个单独的数组。

以下是一个例子:

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

每个子数组总是具有相同的长度,但是可能有两个以上的子数组。

6 个答案:

答案 0 :(得分:0)

使用array.reduce()返回添加值的数组,迭代每个子数组并返回结果数组( accumulator 参数)。在传递给 reduce()的回调中,使用array.forEach()迭代子数组中的每个元素。

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++))等。有关减少功能技术优势的更多阅读( ),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上的jsperf.com,此答案中的代码段更快,而不是接受的答案。

答案 1 :(得分:0)

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

非常简单。这适用于两个维度中的任何数量的事物。

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];            
        }
    }
}

答案 3 :(得分:0)

你可以这样做:

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);

答案 4 :(得分:0)

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

&#13;
&#13;
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);
&#13;
&#13;
&#13;

答案 5 :(得分:0)

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>