Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lodash indexBy with not uniq keys

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 }] }
like image 820
Ubi Avatar asked Jan 11 '15 14:01

Ubi


People also ask

Is Lodash still needed?

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.

How do you find the index of an element in an array Lodash?

The lodash _. indexOf() method is used to get the index of first occurrence of the particular element in the array.

How can we get values from object using Lodash?

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.

Is array equal Lodash?

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.


1 Answers

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 } ] }
like image 166
thefourtheye Avatar answered Sep 19 '22 11:09

thefourtheye