Hi i want to sort an array of objects in javascript. Below is the example data.
const example = [
{
name: "c_name",
children: [{
name: "child",
email: "[email protected]",
children: [{
name: "nested_child",
email: "[email protected]",
}]
}]
},
{
name: "a_name",
children: [{
name: "some_name",
email: "[email protected]",
children: []
}]
},
{
name: "name",
children: [{
name: "child_name",
email: "[email protected]",
children: []
}]
}
];
Should sort this array based on property 'name' and the children object should be sorted again based on 'name' property.
So the expected output is like below, and would like to retain other properties as well like email property in children.
a_name some_name c_name child nested_child name child_name
What i have done...i have a sort function that sorts the array by name property. however dont know how to sort the children object with name property.
const sorted_example = example.sort(this.sort_by_name());
sort_by_name = () => {
return (a, b) => {
let result;
const a_value = a.name.toLowerCase();
const b_value = b.name.toLowerCase();
if (a_value > b_value) {
result = 1;
} else if (a_value < b_value) {
result = -1;
} else {
result = 0;
}
return result;
};
};
Could someone help me how to continue with this. thanks.
The previous answers got you there most of the way but you need to sort again if an item has children. In my example I don't mutate the original array (use .slice
to make a shallow copy so .sort
doesn't mutate).
const example = [{"name":"c_name","children":[{"name":"child","email":"[email protected]","children":[{"name":"nested_child","email":"[email protected]"}]},{"name":"b"},{"name":"a"}]},{"name":"a_name","children":[{"name":"some_name","email":"[email protected]","children":[]}]},{"name":"name","children":[{"name":"child_name","email":"[email protected]","children":[]}]}];
const sortRecursive = (data) => {
const recur = (arr) =>
arr
.slice()
.sort((a, b) => a.name.localeCompare(b.name))
//check each item to see if it has children that is an array
.map(
(item) =>
//if item has children that is an array then sort that
// and it's childrens childrens children
Array.isArray(item.children)
? {
...item,
children: recur(item.children),
}
: item, //no children, just return the item
);
return recur(data);
};
//note that sortRecursive does not change example but returns a new array
// that is sorted
console.log(sortRecursive(example));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments