I have a nested array which is like this:
var data = [
{floor: '2', id: '10002', label: 'Elutuba', items: Array(3)}
{floor: '0', id: '10008', label: 'Saun', items: Array(2)},
{floor: '0', id: '10010', label: 'test2', items: Array(2)},
{floor: '0', id: '10011', label: 'test3', items: Array(2)}
]
From this array, i need to look through the matching floor values and create a arrays which matches and which doesn't. Like this:
var data2 = [
{floor: '0', id: '10008', label: 'Saun', items: Array(2)},
{floor: '0', id: '10010', label: 'test2', items: Array(2)},
{floor: '0', id: '10011', label: 'test3', items: Array(2)}
]
var data3 = [{floor: '2', id: '10002', label: 'Elutuba', items: Array(3)}]
How can i do that?
Here's what i have tried :
var newData = []
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data.length; j++) {
return newData.push(data[i].floor === data[j].floor);
}
}
Try this code below, i don't know if it will meet your expectations
var data2 = [
{floor: '0', id: '10008', label: 'Saun', items: Array(2)},
{floor: '2', id: '10010', label: 'test2', items: Array(2)},
{floor: '0', id: '10011', label: 'test3', items: Array(2)}
]
var data3 = [{floor: '2', id: '10002', label: 'Elutuba', items: Array(3)}]
var newData = [];
for (var i = 0; i < data2.length; i++) {
const foundIndex = data3.findIndex( elt => elt.floor === data2[i].floor );
if(foundIndex != -1){
newData.push(data3[foundIndex]); // Here you can do some merge, i just take in data3
data2.splice(i, 1);
data3.splice(foundIndex, 1);
}
}
console.log(newData)
I have prepared a possible solution to your problem.
const data2 = [
{floor: '2', id: '10002', label: 'Elutuba', items: Array(3)},
{floor: '0', id: '10008', label: 'Saun', items: Array(2)},
{floor: '0', id: '10010', label: 'test2', items: Array(2)},
{floor: '0', id: '10011', label: 'test3', items: Array(2)}
];
const data3 = [];
for (let i = 0; i < data2.length; i++) {
if (data2[i].floor !== data2[i+1].floor) {
data3.push(data2[i]);
break;
}
}
console.log(data3);
Welcome to Stack Overflow. Your problem is about partitioning your array into two arrays and can be solved in multiple ways, once is use the Array.reduce method and check if every array's curr element satisfies your boolean condition curr.floor === floor or not, so deciding in which of the two arrays put the element:
const data = [
{floor: '2', id: '10002', label: 'Elutuba', items: Array(3)},
{floor: '0', id: '10008', label: 'Saun', items: Array(2)},
{floor: '0', id: '10010', label: 'test2', items: Array(2)},
{floor: '0', id: '10011', label: 'test3', items: Array(2)}
];
function groupBy(data, floor) {
const result = data.reduce(function(acc, curr) {
acc[(curr.floor === floor) ? 0 : 1].push(curr);
return acc;
}, [[], []]);
return result;
}
console.log(groupBy(data, '0'));