1

Assume there are two arrays like this:

const element = ['abc', 'def']`

const total = [
  { _id: 'foo', something: 'else' }
  { _id: 'abc' },
  { _id: 'bar' },
  { _id: 'def' }
]

I need to find the element items in the total array and return the index value. So the result should be

[1, 3]

I thought of using a loop and look up with indexOf, but that is not the correct way:

element.forEach(e => {
  total.indexOf(e)
})

2 Answers 2

3

Your original test of total.indexOf(e) doesn't search for the object with its _id property value being e - it searches for whether the object equals the 'abc' or 'def' string, which is of course never true.

Instead, you can use reduce:

const element = ['abc', 'def'];

const total = [
  { _id: 'foo', something: 'else' },
  { _id: 'abc' },
  { _id: 'bar' },
  { _id: 'def' }
];

const foundIndicies = total.reduce((a, { _id }, i) => {
  if (element.includes(_id)) a.push(i);
  return a;
}, []);
console.log(foundIndicies);

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

Comments

1

You can map over element with a variable e, and use Array.prototype.findIndex() on the total array to find the index of the first dictionary that contains e as one of its values, which you can retrieve using Object.values:

const element = ['abc', 'def'];

const total = [
  { _id: 'foo', something: 'else' },
  { _id: 'abc' },
  { _id: 'bar' },
  { _id: 'def' }
];

const locations = element.map(e => total.findIndex(d => Object.values(d).includes(e)))

console.log(locations);

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.