Home > OS >  The last of the objects in the array that have the same value
The last of the objects in the array that have the same value

Time:06-22

const obj = [
{
    id:1,
    info : [
        {
            status:"open",
            value:300
        },
        {
            status:"closed",
            value:1
        },
        {
            status:"open",
            value:100
        }
    ]
},
{
    id:2,
    info : [
        {
            status:"open",
            value:40
        },
        {
            status:"closed",
            value:1
        },
        {
            status:"open",
            value:150
        },
        {
            status:"open",
            value:250
        },
        {
            status:"closed",
            value:10
        }
    ]
}
]

What I want to do is filter by the value of the last one whose status is open.

For example, if I want to find values greater than 200, it should only return me with an id of 2. Because the last status value of the object whose id is 2 is 250.

I tried something like this, but the status is filtering by all that are open.

const filtered = obj.filter(o => {
  return o.info.find(value => {
    if (value.status == "open") {
      if(value.value > 200){
      return true;
    }
  };
 });
});
console.log(filtered)

CodePudding user response:

const filtered = obj.filter(o => {
  for (let i = o.info.length - 1; i >= 0; i--) {
    if (o.info[i].status === 'open') {
      return o.info[i].value > 200
    }
  }
  return false;
});

CodePudding user response:

You can find the last "open" record, by executing find() after reversing the array:

const data = [{
  id: 1,
  info: [
    { status: "open", value: 20 }, 
    { status: "closed", value: 1 },
    { status: "open", value: 100 }
  ]
}, {
  id: 2,
  info: [
    { status: "open", value: 40 },
    { status: "closed", value: 1 },
    { status: "open", value: 150 },
    { status: "open", value: 250 },
    { status: "closed", value: 10 }
  ]
}];

const fn = (data, value) => data.filter(
  ({info}) => [...info.reverse()].find(
    ({status}) => status === 'open'
  )?.value > value
).map(({id}) => id);

console.log(fn(data, 200));

Note that reverse() changes the array in place. To avoid the original data being modified, I spread the array into a new array.

  • Related