Re-create an array from a 2-dimensional array

Here is my problem at the moment. Let's say I have several arrays in an array like:

array[
    array["3", 20160502, "0"],
    array["5", 20160503, "1"],
    array["1", 20160504, "0"],
    array["8", 20160504, "2"],
    array["30", 20160506, "2"],
    array["23", 20160506, "1"],
    array["34", 20160506, "0"],
]

The 0th element is the total counter, the 1st element is the date in quantity, the second element is the status (0 or 1 or 2). I would like to rebuild the array above and create a new array, as shown below:

array[
    array[20160502, "3", "0", "0"],
    array[20160503, "0", "5", "0"],
    array[20160504, "1", "0", "8"],
    array[20160506, "34", "23", "30"]
]

Somebody knows? Thank you so much in advance.

+4
source share
5 answers

You can use the Array#forEach()object as a hash table for the desired groups.

var array = [["3", 20160502, "0"], ["5", 20160503, "1"], ["1", 20160504, "0"], ["8", 20160504, "2"], ["30", 20160506, "2"], ["23", 20160506, "1"], ["34", 20160506, "0"]],
    grouped = []

array.forEach(function (a) {
    if (!this[a[1]]) {
        this[a[1]] = [a[1], '0', '0', '0'];
        grouped.push(this[a[1]]);
    }
    this[a[1]][1 + +a[2]] = a[0];
}, Object.create(null));

console.log(grouped);
Run codeHide result
0
source

Try the following: -

var data = new Array(
    Array("3", 20160502, "0"),
    Array("5", 20160503, "1"),
    Array("1", 20160504, "0"),
    Array("8", 20160504, "2")
 );
 for(i in data){
     [x,y,z] = data[i];
     [x,y,z] = [y,z,x];
     data[i]=[x,y,z];
}
+1
source

map :

var orig = [
    ["3", 20160502, "0"],
    ["5", 20160503, "1"],
    ["1", 20160504, "0"],
    ["8", 20160504, "2"],
    ["30", 20160506, "2"],
    ["23", 20160506, "1"],
    ["34", 20160506, "0"]
]
  
var reordered = orig.map(function(element) {
    return [element[1], element[0], element[2]];
})

console.log(reordered);
Hide result
0

ES6 - :

for(let i of arr)
  arr[i][a,b,c] = arr[i][c,b,a];
0

forEach

var array = [["3", 20160502, "0"],["5", 20160503, "1"],["1", 20160504, "0"],["8", 20160504, "2"],["30", 20160506, "2"],["23", 20160506, "1"],["34", 20160506, "0"],
], result = [];

array.forEach(function(e) {
  if (!this[e[1]]) {
    this[e[1]] = [e[1], 0, 0, 0];
    result.push(this[e[1]]);
  }
  if(e[2] == 0) {
    this[e[1]][1] = Number(e[0]);
  } else if(e[2] == 1) {
    this[e[1]][2] = Number(e[0]);
  } else if(e[2] == 2) {
    this[e[1]][3] = Number(e[0]);
  }
}, {})

console.log(result)
Hide result
0

All Articles