0

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?

4 Answers 4

2

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);

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

Comments

1

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);

Comments

1

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?

Comments

1

Assuming your statuses and Id are unique :

const statusesId = statusesValues.map(x => statuses.find(y => y.status === x).id)

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.