2

I have two arrays. I want to filter one array which contains objects from another array.

let array1= [{date:1, count:4}, {date:3, count:6}];
let array2= [1,2,3,4];

After filtering these two arrays, I need filtered arrays as below.

let array= [4,0,6,0];

So, the filtered array contains the count for matched date and zero for unmatched values. But I'm getting only matched data.

Here is my code:

let array = _.map(_.filter(array1, function(o){
    return _.includes(array2, o.date);
}), 'count');

Thank you

1 Answer 1

4

You can use map() and find() methods for this. You don't need filter() because for each element you will return count or 0 so you can just use map().

let array1= [{date:1, count:4}, {date:3, count:6}];
let array2= [1,2,3,4];

var array = array2.map(function(e) {
  var f = array1.find(a => a.date == e);
  return f ? f.count : 0
});

console.log(array)

Sign up to request clarification or add additional context in comments.

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.