Home > Net >  Is there a better way to find an specific object inside an array by name?
Is there a better way to find an specific object inside an array by name?

Time:07-15

I know this could be easily done with a loop like I'm doing in the method below. I'm just wondering if there is any pre-build function that I can use to get the same result my code gets here:

const openExerciseListModal = (index:number) =>{
let selectedValue = selectedItems[index];
items.forEach((element,index) => {
  if(element.value===selectedValue){
    alert(index)
  }
});
savedExercises = [...selectedExercise]
setExerciseListModalVisible(() => !isExerciseListModalVisible)

My array is something like this:

[{ label: "Monday", value: "Monday" },{ label: "Tuesday", value: "Tuesday" }]

My goal is to click the button in my screen and get the index of that item in my array. If the user press on Monday, it gets 0 for instance.

CodePudding user response:

I'd probably go with something like:

const index = items.map(({ value }) => value).indexOf(selectedValue)

Map over the items to create an array of the exact thing you are searching for, and then find the index of that thing.


Note: for very large arrays, this may be slow since it's actually looping over the results twice. But for something like days of the week, it's going to be fine.

  • Related