Thomas Jason
Thomas Jason

Reputation: 568

How to make filter using map in JS

I want to make some filter in javascript. There is an array of riders and when ID of rider is inside of orders, it passes by filter.
I made this filter.

let riders = [1, 2, 3, 4, 5];

const orders = [{ Id: 1 }, { Id: 3 }, { Id: 1 }];

const ho = riders.filter((index) => {
  orders.map((order) => order.Id === index) === true;
});

And I want to get the result like

console.log(ho) // [1, 3]

But the result gives [ ].
How can I make this correctly using filter or map or other methods of array without for loop?
Thank you so much for reading it.

Upvotes: 0

Views: 39

Answers (3)

charlietfl
charlietfl

Reputation: 171679

Using reduce() and a Set to store the order ID's.

A Set only contains unique values and is a more efficient lookup object than an array

const riders = [1, 2, 3, 4, 5],
    orders = [{ Id: 1 }, { Id: 3 }, { Id: 1 }],
    orderIds = orders.reduce((a,{Id})=> a.add(Id), new Set),
    ho = riders.filter(id => orderIds.has(id));
    
console.log(ho)

Upvotes: 0

brk
brk

Reputation: 50291

Use reduce and in callback check if the Id is present in riders. This acc.indexOf(curr.Id) === -1 will prevent duplicate in accumulator array

let riders = [1, 2, 3, 4, 5];
const orders = [{
  Id: 1
}, {
  Id: 3
}, {
  Id: 1
}];
const filter = orders.reduce((acc, curr) => {
  if (riders.includes(curr.Id) && acc.indexOf(curr.Id) === -1) {
    acc.push(curr.Id)
  }

  return acc;
}, []);

console.log(filter)

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44087

Just extract the IDs from orders using map, then use filter and includes. Also note that you're using => { (block function notation), which doesn't implicitly return - so you need a return if you're using => {, but don't if you use =>.

let riders = [1, 2, 3, 4, 5];

const orders = [{ Id: 1 }, { Id: 3 }, { Id: 1 }];

const id = orders.map(({ Id }) => Id);

const ho = riders.filter(e => id.includes(e));

console.log(ho);

You could do it without the id array if you use findIndex:

let riders = [1, 2, 3, 4, 5];

const orders = [{ Id: 1 }, { Id: 3 }, { Id: 1 }];

const ho = riders.filter(item => orders.findIndex(({ Id }) => item == Id) != -1);

console.log(ho);

Upvotes: 2

Related Questions