Home > Mobile >  get data and index when filtering data in array of object javascript
get data and index when filtering data in array of object javascript

Time:09-15

i am trying to get data and index in same time using filter in javascript.

i have this array of object :

[
{
number: 123,
name: test1
},
{
number: 1234,
name: test14

},
{
number: 1235,
name: test15

},
{
number: 1236,
name: test16

},
]

by using filter:

let object = array.filter((value) => {

  return value.number == 1235;

}

Returning output of object successfully.

My goal is how to return index of this output in same code?

that mean return object value and index.

Without need to filter array again to get the index of value.

CodePudding user response:

You can get index first:

const idx = array.findIndex((value) => {
  return value.number == 1235;
});

and then get an object:

const obj = array[idx];

CodePudding user response:

It looks like you have a single item that corresponds to the filter criteria, in this case you can use findIndex instead:

let index = array.findIndex(value => value.number == 1235);

You can also just find a single item using find:

let item = array.find(value => value.number == 1235);

Then get the index with indexOf:

let index = array.indexOf(item);

CodePudding user response:

Use this way it will work.

let arr=[
{
number: 123,
name: 'test1'
},
{
number: 1234,
name: 'test14'

},
{
number: 1235,
name: 'test15'

},
{
number: 1236,
name: 'test16'

},
]

let fun = (value,index) => {
  value.index =index
  return value.number == 1235;

}
console.log([...arr].filter((value,index)=>fun(value,index))
)

CodePudding user response:

You can not return anything inside filter though you can modify the object inside filter to add the index but that is not a good practice. Filter should be used to return the filtered object based on the given condition.You can use map with filter

let arr=[
{
number: 1235,
name: 'test1'
},
{
number: 1234,
name: 'test14'

},
{
number: 1235,
name: 'test15'

},
{
number: 1236,
name: 'test16'

},
]

let object = arr.map((obj,index)=>{
return {...obj,index}
}).filter((value) => value.number == 1235)

console.log(object)

Or if you want to loop once only then use foreach

    let arr=[
    {
    number: 1235,
    name: 'test1'
    },
    {
    number: 1234,
    name: 'test14'

    },
    {
    number: 1235,
    name: 'test15'

    },
    {
    number: 1236,
    name: 'test16'

    },
    ]

    let objct = [];
    arr.forEach((obj,index)=>{
      if(obj.number ==1235){
          objct.push({...obj,index})
      }
    })

    console.log(objct)

  • Related