Here is my problem at the moment. Let's say I have some arrays in a array like following:
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"],
]
0th element is total count, 1st element is date in number, 2nd element is status(0 or 1 or 2). I would like to rearrange the array above and create a new array like below:
array[
array[20160502, "3", "0", "0"],
array[20160503, "0", "5", "0"],
array[20160504, "1", "0", "8"],
array[20160506, "34", "23", "30"]
]
Does anyone have a clue? Thank you so much in advance.
You can use map to reorder:
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);
With ES6 you can do something like this:
for(let i of arr)
arr[i][a,b,c] = arr[i][c,b,a];
You could use Array#forEach()
and an object as hash table for the wanted groupes.
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);
Try this:-
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];
}
You can do this with 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.