admin管理员组

文章数量:1197776

I have 2 arrays of objects. How can I get the index of the id in the first array that matches the object in the second array that has isPrimary set to true? Only one object in the second array will ever have isPrimary: true.

let items= [
  {
    "id": 1,
    "color" "red"
  },
  {
    "id": 2,
    "color": "green"
  },
  {
    ...
  },
  ...
]


let items2= [
  {
    "age": 18,
    "isPrimary" false
  },
  {
    "age": 25,
    "isPrimary": true
  },
  {
    ...
  },
  ...
]

I have 2 arrays of objects. How can I get the index of the id in the first array that matches the object in the second array that has isPrimary set to true? Only one object in the second array will ever have isPrimary: true.

let items= [
  {
    "id": 1,
    "color" "red"
  },
  {
    "id": 2,
    "color": "green"
  },
  {
    ...
  },
  ...
]


let items2= [
  {
    "age": 18,
    "isPrimary" false
  },
  {
    "age": 25,
    "isPrimary": true
  },
  {
    ...
  },
  ...
]
Share Improve this question asked Jan 23 at 18:31 noclistnoclist 1,8194 gold badges31 silver badges73 bronze badges 2
  • Please edit your code to be a minimal reproducible example without pseudocode, so we can work on it as-is in our IDEs. • Also, what specific output are you looking for? What is the “index” of the id? • You might want to tag this as JavaScript instead of or in addition to TypeScript, because this looks like a runtime question. – jcalz Commented Jan 23 at 18:37
  • 1. Find the index of the item with isPrimary in items2 2. use items[indexThatYouFound] – VLAZ Commented Jan 23 at 18:40
Add a comment  | 

1 Answer 1

Reset to default 1

If you just want to get the item in items that has the same index as the item in items2 with isPrimary set to true you can use findIndex on array to get that index, findIndex and find both take as an argument a callback function that will be evaluated against each element in the array, the function should return a boolean, and the first value of the array to satisfy the predicate represents by the function will be returned, or its index if using findIndex, so

const index = items2.findIndex((obj) => obj.isPrimary);

then you can get the item by indexing the items array

const item = items[index]

you could combine these steps by using find on items array and using the second argument of the callback, which is the current index, to check items values at that index

const item = items.find((_,i)=>items2[i].isPrimary);

本文标签: typescriptFinding array index based on match from second arrayStack Overflow