skip to Main Content

I want to filter an array of objects based on a specific condition. Specifically, I want to exclude the object with an ID equal to a given value and all objects that appear before the first object that doesn’t satisfy this condition. How can I achieve this using a single loop?

Here’s an example array:

const arr = [{ id: 10 }, { id: 20 }, { id: 30 }, { id: 40 }, { id: 50 }, { id: 60 }];

Let’s say I have a target ID:

const myID = 25;

I want to filter the array to get the following result:

const result = [{ id: 20 }, { id: 30 }, { id: 40 }, { id: 50 }, { id: 60 }];

3

Answers


  1. You can achieve this using a combination of filter and find array methods. Here’s how you can do it:

    const arr = [{id: 10}, {id: 20}, {id: 30}, {id: 40}, {id: 50}, {id: 60}];
    const myID = 25;
    
    const result = arr.filter(item => item.id > myID || item.id === arr.find(i => i.id !== myID).id);
    
    console.log(result);
    

    This will give you the desired result:

    [
      { id: 20 },
      { id: 30 },
      { id: 40 },
      { id: 50 },
      { id: 60 }
    ]
    
    Login or Signup to reply.
  2. const arr = [{id: 10}, {id: 20}, {id: 30}, {id: 40}, {id: 50}, {id: 60}]
    
    const myID = 25;
    
    // const result = [{id: 20}, {id: 30}, {id: 40}, {id: 50}, {id: 60}]
    
    let result = [];
    let lessOne ={id : Number.MIN_VALUE} ;
    
    for(let obj of arr) {
      if(obj.id > myID) {
        result.push(obj)
      } else {
        if(obj.id > lessOne.id) {
          lessOne = obj;
        }
      }
    }
    
    result.unshift(lessOne);
    
    
    console.log(result);
    Login or Signup to reply.
  3. const arr = [{ id: 10 }, { id: 20 }, { id: 30 }, { id: 40 }, { id: 50 }, { id: 60 }];
    const myID = 25;
    
    const index = arr.findIndex(obj => obj.id !== myID);
    const result = index !== -1 ? arr.slice(index) : [];
    
    console.log(result);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search