I have an object with multiple arrays of data, and I want to filter out the 0 values and sort them in descending order.
My current solution extracts each value from the objects and puts it into a separate array. However, I am seeking a more efficient and concise approach. Any suggestions would be greatly appreciated!
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
}
]
]