Reputation: 1269
I have 2 arrays
const statusesValues = ['progress', 'validate', 'blocked']
and
const statuses = [{status: 'progress' , id: 1}, {status: 'validate', id: 2}, {status: 'blocked', id: 3}, {status: 'no_validate', id: 4}]
I would like to get an array of id matches between the elements of the first array and the status properties of the second array.
In this example: [1, 2, 3]
What is the most elegant way to do it?
Upvotes: 0
Views: 52
Reputation: 5853
Just use Array#prototype#filter
and Array#prototype#includes
const statusesValues = ['progress', 'validate', 'blocked']
const statuses = [{
status: 'progress',
id: 1
}, {
status: 'validate',
id: 2
}, {
status: 'blocked',
id: 3
}, {
status: 'no_validate',
id: 4
}]
const res = statuses
.filter(x => statusesValues.includes(x.status.toLowerCase()))
.map(x => x.id);
console.log(res);
Upvotes: 1
Reputation: 386550
You could take a Map
and get all id
.
const
statusesValues = ['progress', 'validate', 'blocked'],
statuses = [{ status: 'progress', id: 1 }, { status: 'validate', id: 2 }, { status: 'blocked', id: 3 }, { status: 'no_validate', id: 4 }],
ids = statusesValues.map(
Map.prototype.get,
new Map(statuses.map(({ status, id }) => [status, id]))
);
console.log(ids);
Upvotes: 2
Reputation: 667
Assuming your statuses and Id are unique :
const statusesId = statusesValues.map(x => statuses.find(y => y.status === x).id)
Upvotes: 1
Reputation: 1889
You can do it like this:
const matches = statuses
.filter(status => statusesValues.indexOf(status.status) > -1)
.map(status => status.id);
Is this what you are looking for?
Upvotes: 1