Pratik Kumar
Pratik Kumar

Reputation: 63

Want to remove objects that are before specific value


const array = [{
    id: "U",
    T: "001"
  },
  {
    id: "R",
    T: "002"
  },
  {
    id: "U",
    T: "003"
  },
  {
    id: "R",
    T: "004"
  },
  {
    id: "U",
    T: "005"
  },
]

Above array can have multiple objects with id: 'R' and i want to ignore all objects that are before id: 'R'.

Expected:

const array = [
{ id: "U", 
T: "005"}]

Can someone please help with this

Upvotes: 2

Views: 74

Answers (4)

water_ak47
water_ak47

Reputation: 1306

const array = [
  {
    id: "U",
    T: "001",
  },
  {
    id: "R",
    T: "002",
  },
  {
    id: "U",
    T: "003",
  },
  {
    id: "R",
    T: "004",
  },
  {
    id: "U",
    T: "005",
  },
];

/**
 * 
 * @param {array} data
 * @param {string} id  
 * @returns The results you want
 */

function getData(data, id) {
  let lastIndex = 0;

  Array.from(data).forEach((item, index) => {
    if (item.id === id.trim("")) {
      lastIndex = index;
    }
  });

  const result = data.slice(lastIndex + 1);

  return result;
}


console.log(getData(array, "R"));
/*
* Result:
* [{ id: 'U', T: '005' } ]
*/

Upvotes: 0

Nikhil Unni
Nikhil Unni

Reputation: 779

Agree with all the above answers, but why do we go with the map, slice, reverese and all. We can simply use just a loop instead of those as below. Considering time as well, if the array length increases the combination of any of the map, reverse, slice, splice takes much time

const array = [{
    id: "U",
    T: "001"
  },
  {
    id: "R",
    T: "002"
  },
  {
    id: "U",
    T: "003"
  },
  {
    id: "R",
    T: "004"
  },
  {
    id: "U",
    T: "005"
  },
];

let newArr = [];

for(let i = array.length - 1; i >= 0; i--){
if(array[i].id === 'R') break;
else newArr.push(array[i])
}
console.log(newArr);

Upvotes: 1

ikiK
ikiK

Reputation: 6532

Reverse array, Find the index of first R, slice array...

const array = [{
    id: "U",
    T: "001"
  },
  {
    id: "R",
    T: "002"
  },
  {
    id: "U",
    T: "003"
  },
  {
    id: "R",
    T: "004"
  },
  {
    id: "U",
    T: "005"
  }
]

const cheak = (element) => element.id === "R"


console.log(array.reverse().slice(0, array.findIndex(cheak)).reverse());

Upvotes: 0

Majed Badawi
Majed Badawi

Reputation: 28424

const array = [ { id: "U", T: "001" }, { id: "R", T: "002" }, { id: "U", T: "003" }, { id: "R", T: "004" }, { id: "U", T: "005" } ];

const ids = array.map(({ id }) => id);
const index = ids.lastIndexOf("R") + 1;
const res = array.splice(index);

console.log(res);

Upvotes: 2

Related Questions