I am looking for adding an object into an already sorted array of object. So that new array should be sorted after adding the new object into it.
Here is my sorted Array based on object property displayName
[
{
"id": "06BCCC25",
"displayName":"Application"
},
{
"id": "39F886D9",
"displayName":"Communication"
},
{
"id": "22EA4ED5",
"displayName":"Device"
},
{
"id": "2F6E5FEA",
"displayName":"Service"
},
{
"id": "317BF72C", "displayName":"Service02"
}
]
now I want to add
{
"id": "07BSSC25",
"displayName":"Mail"
}
so after adding it will be placed between 3rd and 4th index.
You can use _.sortedIndexBy()
for that, see:
For example you could use:
array.splice(_.sortedIndexBy(array, value, iteratee), 0, value);
where array
is your array of objects, value
is the new object to insert and iteratee
is a function invoked per element that returns the value that you want to sort it by, but it also can be a property name.
So in your case something like this should work:
array.splice(_.sortedIndexBy(array, value, 'displayName'), 0, value);
Just substitute your array name for array
and the new object for value
.
See also this issue on GitHub where it is explained:
You might also add a lodash function if you use it a lot, for example:
_.insertSorted = (a, v) => a.splice(_.sortedIndex(a, v), 0, v);
_.insertSortedBy = (a, v, i) => a.splice(_.sortedIndexBy(a, v, i), 0, v);
And you could use - in your case
_.insertSorted(array, value, 'displayName');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With