@Tanjore, it would be beneficial for you to organize your ids within an object structure like this.
For all the ids with the value of 5
, which is 1
, you can use {'5': [1]}
.
Similarly, for ids with the value of 6
, which is 3
, you can utilize {'3': [3]}
.
And for ids with the value of 7
, encompassing 2, 3, 4
, you can structure it as {'7': [2, 3, 4]}
.
...
You can establish an object resembling this format:
{
"5": [
1
],
"6": [
3
],
"7": [
2,
4,
6
],
"8": [
5
]
}
To achieve this object in a Node REPL environment, follow the steps below:
> var arr = [
... {id:1,val: 5,name: 'Josh'},
... {id:2,val: 7,name: 'John'},
... {id:3,val: 6,name:'mike'},
... {id:4,val: 7,name: 'Andy'},
... {id:5,val: 8,name: 'Andrew'},
... {id:6,val: 7,name: 'Dave'}
... ]
undefined
>
> var obj = {}
undefined
>
> arr.forEach((item) => {
... if (obj[item['val']] === undefined) {
..... obj[item['val']] = [item['id']];
..... } else {
..... obj[item['val']].push(item['id']);
..... }
... })
undefined
>
> obj
{ '5': [ 1 ], '6': [ 3 ], '7': [ 2, 4, 6 ], '8': [ 5 ] }
>
> JSON.stringify(obj, undefined, 4)
'{\n "5": [\n 1\n ],\n "6": [\n 3\n ],\n "7": [\n 2,\n 4,\n 6\n ],\n "8": [\n 5\n ]\n}'
>
> console.log(JSON.stringify(obj, undefined, 4))
{
"5": [
1
],
"6": [
3
],
"7": [
2,
4,
6
],
"8": [
5
]
}
undefined
>
Finally, by implementing the above approach, you will obtain the desired array structure as illustrated below:
[
{
"id": 1,
"val": 5,
"name": "Josh"
},
{
"id": 3,
"val": 6,
"name": "mike"
},
{
"id": [
2,
4,
6
],
"val": 7,
"name": [
"John",
"Andy",
"Dave"
]
},
{
"id": 5,
"val": 8,
"name": "Andrew"
}
]
Feel free to refer to the code snippet provided below to generate the desired array structure:
// Input array
var arr = [
{id:1,val: 5,name: 'Josh'},
{id:2,val: 7,name: 'John'},
{id:3,val: 6,name:'mike'},
{id:4,val: 7,name: 'Andy'},
{id:5,val: 8,name: 'Andrew'},
{id:6,val: 7,name: 'Dave'}
]
// Empty array for resulting data and easier grouping based on 'val'
var obj = {};
arr.forEach((item) => {
if (obj[item['val']] === undefined) {
obj[item['val']] = item;
} else {
var id = obj[item['val']]['id'];
var name = obj[item['val']]['name'];
if(typeof id === 'number'){
obj[item['val']]['id'] = [id, item['id']];
obj[item['val']]['name'] = [name, item['name']];
} else { // 'object'
obj[item['val']]['id'].push(item['id']);
obj[item['val']]['name'].push(item['name']);
}
}
})
var newArr = Object.values(obj);
// console.log(newArr);
// Beautify the resulting array
console.log(JSON.stringify(newArr, undefined, 4));
/*
[
{
"id": 1,
"val": 5,
"name": "Josh"
},
{
"id": 3,
"val": 6,
"name": "mike"
},
{
"id": [
2,
4,
6
],
"val": 7,
"name": [
"John",
"Andy",
"Dave"
]
},
{
"id": 5,
"val": 8,
"name": "Andrew"
}
]
*/