I'm given an Object of n length, with x amount of arrays in the object. I would like not to include the 0's, and to be sorted in descending order.
I've made a simple solution, that takes the value in each object, and takes the nth value and puts that in an array, but am looking for something more robust and shorter; any help would be helpful!
const arr = {
"rows": [{
"value": "demo value 1",
"data": [15, 45, 0, 0]
}, {
"value": "demo value 2",
"data": [11, 87, 0, 0]
}, {
"value": "demo value 3",
"data": [8, 113, 0, 0]
}, {
"value": "demo value 4",
"data": [7, 26, 0, 2]
}, {
"value": "demo value 5",
"data": [7, 3, 0, 0]
}, {
"value": "demo value 6",
"data": [6, 17, 0, 1]
}]
};
let newArr = [];
let newArr2 = [];
let newArr3 = [];
let newArr4 = [];
for (i = 0; i < arr.rows.length; i ) {
if (arr.rows[i].data[0] != 0)
newArr.push({
value: arr.rows[i].value,
data: arr.rows[i].data[0]
})
if (arr.rows[i].data[1] != 0)
newArr2.push({
value: arr.rows[i].value,
data: arr.rows[i].data[1]
})
if (arr.rows[i].data[2] != 0)
newArr3.push({
value: arr.rows[i].value,
data: arr.rows[i].data[2]
})
if (arr.rows[i].data[3] != 0)
newArr4.push({
value: arr.rows[i].value,
data: arr.rows[i].data[3]
})
/// ... and so on
}
console.log(newArr)
console.log(newArr2)
console.log(newArr3)
console.log(newArr4)
EDIT:
Expected result:
[
[
{
"value": "demo value 1",
"data": 15
},
{
"value": "demo value 2",
"data": 11
},
{
"value": "demo value 3",
"data": 8
},
{
"value": "demo value 4",
"data": 7
},
{
"value": "demo value 5",
"data": 7
},
{
"value": "demo value 6",
"data": 6
}
],
[
{
"value": "demo value 3",
"data": 113
},
{
"value": "demo value 2",
"data": 87
},
{
"value": "demo value 1",
"data": 45
},
{
"value": "demo value 4",
"data": 26
},
{
"value": "demo value 6",
"data": 17
},
{
"value": "demo value 5",
"data": 3
}
],
[],
[
{
"value": "demo value 4",
"data": 2
},
{
"value": "demo value 6",
"data": 1
}
]
]
CodePudding user response:
I'm not quite sure if this is what you're after as there is no "expected format" provided - however this may put you on the right track
let new_arrays = [];
for (let i = 0; i < arr.rows.length; i ) {
let current_row = arr.rows[i];
for (let j = 0; j < current_row.data.length; j ) {
let current_data = current_row.data[j];
if(current_data === 0){
continue;
}
if(new_arrays[j] === undefined){
new_arrays[j] = [];
}
new_arrays[j].push({
value: current_row.value,
data : current_data,
});
}
}
console.log(new_arrays);
NOTE: if all values at an index are 0 (or the index doesn't exist), there will be no "new array" at that index
