Seeking assistance for the following task: I am trying to create a new multidimensional array of objects based on an existing array of objects:
[
{number:111, connectedNumber: 112, ...},
{number:112, connectedNumber: 111, ...},
{number:113, connectedNumber: 114, ...},
{number:114, connectedNumber: 113, ...}
....
]
Ultimately, I want to generate a new multidimensional array containing groups of related objects:
[
[{number:111, connectedNumber: 112, ...}, {number:112, connectedNumber: 111, ...}],
[{number:113, connectedNumber: 114, ...}, {number:114, connectedNumber: 113, ...}],
]
These objects are related by number === connecetedNumber
.
Currently, my approach involves creating a new array and iterating through the original list of objects to check if number === connecetedNumber
and then adding them to the new array:
for (let j = count; numbers.length > j; j++) {
organizedNumber.push([numbers[j]]);
for (let k = j; numbers.length > k; k++) {
if (numbers[j].number === numbers[k].connectedNumber) {
organizedNumber[j].push(numbers[k]);
}
}
}
However, this results in a new array structured like this:
[
[{number:111, connectedNumber: 112, ...}, {number:112, connectedNumber: 111, ...}],
[{number:112, connectedNumber: 111, ...}],
[{number:113, connectedNumber: 114, ...}, {number:114, connectedNumber: 113, ...}],
[{number:114, connectedNumber: 113, ...}],
....
]
The loop is iterating over each element as expected, but it also adds elements that have already been included in the previous array.
If you have any suggestions or guidance, please let me know. Thank you.