1

Is there a way to retrieve an element from inner array in array when using nested lodash find, for example?

I have an array of groups, each element of which has array of children. All children have unique ids (even between groups). I need to get hold of a child with id == value and now I'm doing the following:

  1. Firstly I retrieve needed group:

    var group = _(groups).find(g => {return _(g.children).find(c => {return c.id == value})});

  2. Then I get the child:

    var child = _(group.children).find(c => {return c.id == value});

Is there a more efficient and elegant way to achieve this?

2
  • why lodash? native javascript (filter(), map(), etc) are not enough? Commented Nov 21, 2016 at 8:42
  • no idea, we just use it in our project :-) Commented Nov 21, 2016 at 14:35

2 Answers 2

4

flat groups by children and find from result

_(groups)
    .flatMap('children')
    .find({id: value})
    .value();
Sign up to request clarification or add additional context in comments.

Comments

1

There is a another way of doing this using map() and filter()

var filteredArray = [];

_.map(group, function(groupValue) {
  var groupChildren = groupValue.children;
  var filteredChild = _.filter(groupChildren, function(child) {
    return child.id = value
  });
   if(filteredChild.length != 0) {
     filteredArray.push(filteredChild[0]);
     return groupValue;
   } else {
     return groupValue;
   }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.