Home > Mobile >  Find index of element in a List
Find index of element in a List

Time:08-01

I have an List and I am trying to find if there is any "DishId" with value 63 and if found , i wanted to return the object count of the element, for example here I wanted to return 1 as it is the first object in the list. Below is the list :

  result =  [ TextRow {
        BagId: 'BTWDCZ46826',
        BagStatus: 1,
        DishId: 63,
        SellerId: 205,
        Qty: 1,
        PreperationTime: 240 
        } ,
        {
        BagId: 'BTWDCZ46234',
        BagStatus: 1,
        DishId: 69,
        SellerId: 195,
        Qty: 1,
        PreperationTime: 150 
        } 
    ]

Below is the code that I tried to find if DishId with 63 is found or not

if(results.find(({ DishId }) => dishId === req.body.dishId)){
       index = results.indexOf(({ DishId }) => x.dishId === req.body.dishId).DishId;
       console.log("Found");
       console.log("Index is ", index);
}

CodePudding user response:

const result = [{
        BagId: 'BTWDCZ46826',
        BagStatus: 1,
        DishId: 63,
        SellerId: 205,
        Qty: 1,
        PreperationTime: 240 
        } ,
        {
        BagId: 'BTWDCZ46234',
        BagStatus: 1,
        DishId: 69,
        SellerId: 195,
        Qty: 1,
        PreperationTime: 150 
        } 
    ];

const idx = result.findIndex(el => el.DishId === 69);
console.log(idx);

Also, there was an error in your result array. Btw, findIndex returns -1 if searched element is not present. See findIndex MDN Page

CodePudding user response:

You need the Index not the object found itself, So use findIndex instead of find:

const arr = [{
    BagId: 'BTWDCZ46826',
    BagStatus: 1,
    DishId: 63,
    SellerId: 205,
    Qty: 1,
    PreperationTime: 240
  },
  {
    BagId: 'BTWDCZ46234',
    BagStatus: 1,
    DishId: 69,
    SellerId: 195,
    Qty: 1,
    PreperationTime: 150
  }
]
console.log(arr.findIndex(({
  DishId
}) => DishId === 63))

I wanted to return 1 as it is the first object

It gonna return 0 not 1, since array in JS are zero based

  • Related