Let's dive into the trick and get our hands dirty. This roadmap isn't a direct solution, but once you understand it, you can narrow it down to a function that suits your specific needs.
data = [
{ name : 'Alice', age : 21},
{ name : 'Henry', age : 20 },
{ name : 'Max', age : 20 },
{ name : 'Jane', age : 21}
]
Now, we need to search and reduce the given set of unique age values through loops. We declare a set of variables to work with:
var a = [];
var c= [];
var i;
var ii;
var iii;
var iv;
Next, let's loop through the entire process:
for (i = 0; i < data.length; i++) {
a.push(data[i].age)
}
a=[...new Set(a)];
This provides us with unique age values as an array from the data array. One problem solved. Now, we create a placeholder array from the newly generated unique array:
for (ii = 0; ii < a.length; ii++) {
c.push({'age':a[ii], 'name':[]})
}
With placeholders set according to the unique array, we search and match from the data array and populate the name array in the placeholder array:
for (iii = 0; iii < c.length; iii++) {
for (iv = 0; iv < data.length; iv++) {
if(data[iv].age == c[iii].age){c[iii].name.push(data[iv].name)}
}
}
It's as simple as that. You can create multiple functions to make it more organized, but this is the basic roadmap to tackle the issue.
// JavaScript code snippet
// Data manipulation example
var a = [];
var c= [];
var i;
var ii;
var iii;
var iv;
for (i = 0; i < data.length; i++) {
a.push(data[i].age);
}
a=[...new Set(a)];
for (ii = 0; ii < a.length; ii++) {
c.push({'age':a[ii], 'name':[]});
}
for (iii = 0; iii < c.length; iii++) {
for (iv = 0; iv < data.length; iv++) {
if(data[iv].age == c[iii].age){c[iii].name.push(data[iv].name);}
}
}
console.log(c);
On a side note, this kind of data manipulation scenario is common in everyday tasks. I've integrated functions into my JS framework to handle searching, comparing, and populating arrays based on any given value. If I find time, I'll share the source code here.