0

I have a two arrays, and I want to match their ID values and then get the index of that id in the second array. I know this sounds simple but I'm super new to the syntax, and I'm having a hard time picturing what this should look like. can anyone model that in simple terms?

example functionality:

var array1 = { id:2, name: 'preston'}

array2 = {
{
   id: 1
   name: 'john'
},
{
   id: 2
   name: 'bob'
}

Expected behavior

where both ids = 2, give index of array2. returns 1

can anyone show me?

2
  • What would the inputs to your function be? Two arrays and the id you are looking for in them? Commented Oct 9, 2019 at 17:00
  • Those are not arrays. Arrays have brackets [] and contain list of objects or primitive values. Commented Oct 9, 2019 at 17:08

2 Answers 2

3

You can use findIndex on array2

Try this:

var array1 = {
  id: 2,
  name: 'preston'
}

var array2 = [{
    id: 1,
    name: 'john'
  },
  {
    id: 2,
    name: 'bob'
  }
]

console.log(array2.findIndex(item => item.id === array1.id))

Or use indexOf with map if you want support for IE as well without polyfills.

var array1 = {
  id: 2,
  name: 'preston'
}

var array2 = [{
    id: 1,
    name: 'john'
  },
  {
    id: 2,
    name: 'bob'
  }
]

console.log(array2.map(item => item.id).indexOf(array1.id))

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

Comments

1

Iterate over each item in array1 using forEach(). Find each item's index in array2 using findIndex().

var array1 = [{id:2, name: "preston"}];
var array2 = [{id: 1, name: "john" }, {id: 2, name: "bob" }];

array1.forEach(item => {
  let index = array2.findIndex(obj => obj.id === item.id);  
  console.log(index);
});

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.