skip to Main Content

I have an array

const obj=[{fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 5, smu: 3, stowage: 5, index: "FC-093"},
 {fullCart: 5, halfCart: 7, smu: 3, stowage: 5, index: "FC-093"}
 ]

I need to retain the last object in the array ie whichever is the previous object with same property here index:’FC-093′ should be removed. ie the result should be,

[{fullCart: 5, halfCart: 7, smu: 3, stowage: 5, index: "FC-093"}]

2

Answers


  1. I am not entirely sure I fully understand your question. If you simply want to return the last entry you can do:

    
        function returnLast(arr) {
            let index = arr.length - 1;
            return arr[index];
        }
    
    

    If you wanted to remove that last entry then you could make a new array and set the old one equal to the new one:

    
    let array = [0, 1, 2, 3, 4, 5]
    
    function makeNewArray(arr) {
        return arr.slice(0, -1);
    }
    
    array = makeNewArray(array);
    // array == [0, 1, 2, 3, 4]
    
    
    Login or Signup to reply.
  2. This is probably what you need.

    1. You get every unique index value in an array using .map() method
    2. You loop thru your unique array now and use the findLast method to get the last element in your obj array per value in your unique array and push it in your result array
    const obj=[
     {fullCart: 5, halfCart: 4, smu: 3, stowage: 5, index: "FC-093"},
     {fullCart: 5, halfCart: 4, smu: 8, stowage: 5, index: "FC-093"},
     {fullCart: 5, halfCart: 4, smu: 0, stowage: 5, index: "FC-093"},
     {fullCart: 5, halfCart: 5, smu: 3, stowage: 5, index: "FC-093"},
     {fullCart: 10, halfCart: 7, smu: 3, stowage: 5, index: "FC-093"},
     {fullCart: 3, halfCart: 6, smu: 4, stowage: 5, index: "FC-095"},
     {fullCart: 3, halfCart: 6, smu: 5, stowage: 5, index: "FC-095"},
     {fullCart: 10, halfCart: 7, smu: 8, stowage: 5, index: "FC-095"},
     {fullCart: 2, halfCart: 8, smu: 10, stowage: 5, index: "FC-098"},
     {fullCart: 10, halfCart: 9, smu: 2, stowage: 5, index: "FC-098"}
    ];
    let result = [];//initialize result array
    
    //create unique array
    const unique = [...new Set(obj.map(item => item.index))];
    console.log(unique)//prints every unique value from key index found in an array 
    
    //loop thru unique array
    unique.forEach(ele => {
      //find last element where index value is present in unique array
      let res = obj.findLast((element) => element.index == ele);
      result.push(res)
    })
    
    console.log(result)//expected output
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search