Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lodash Add Object to already sorted Array of Obejct

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.

like image 984
Sam Avatar asked Mar 27 '17 10:03

Sam


1 Answers

You can use _.sortedIndexBy() for that, see:

  • https://lodash.com/docs/4.17.4#sortedIndexBy

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:

  • https://github.com/lodash/lodash/issues/537

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');
like image 153
rsp Avatar answered Oct 20 '22 04:10

rsp