How I can index array with not uniq keys. I try use lodash indexBy, but it gives not expected result.
var keys = [
{ 'dir': 'left', 'code': 97 },
{ 'dir': 'left', 'code': 100 },
{ 'dir': 'right', 'code': 50 },
{ 'dir': 'right', 'code': 51 }
];
var a = _.indexBy(keys, 'dir');
Result:
{ left: { dir: 'left', code: 100 },
right: { dir: 'right', code: 51 } }
Expected result:
{ left: [{ dir: 'left', code: 100 }, { 'dir': 'left', 'code': 97 }],
right: [{ dir: 'right', code: 51 }, { 'dir': 'right', 'code': 50 }] }
But Sometimes You Do Need Lodash Not every Lodash utility is available in Vanilla JavaScript. You can't deep clone an object, for example. That's why these libraries are far from obsolete. But if you're loading the entire library just to use a couple of methods, that's not the best way to use the library.
The lodash _. indexOf() method is used to get the index of first occurrence of the particular element in the array.
get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.
The Lodash _. isEqual() Method performs a deep comparison between two values to determine if they are equivalent. This method supports comparing arrays, array buffers, boolean, date objects, maps, numbers, objects, regex, sets, strings, symbols, and typed arrays.
You need to use _.groupBy
for that, like this
console.log(_.groupBy(keys, 'dir'));
would print
{ left: [ { dir: 'left', code: 97 }, { dir: 'left', code: 100 } ],
right: [ { dir: 'right', code: 50 }, { dir: 'right', code: 51 } ] }
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