Home > OS >  findLastIndex() not working in FireFox, Javascript
findLastIndex() not working in FireFox, Javascript

Time:02-19

I have an array of duplicate objects.

I have to find allways last duplicate, and remove it from array.

In Chrome i use findLastIndex, to get the index, and remove it. Sadly FireFox does not support that function.

Any other idea how to get last index of duplicate object in array, in simple way?

(to find my object I use property name: string, I dont have Id, thats why I need the Index.

Here is example of array:

[{
    imgSource: "/sushi/test2.png"
    ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce"
    name: "sushi1"
    price: 133
    weight: 120
  },
  {
    imgSource: "/sushi/test2.png"
    ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce"
    name: "sushi1"
    price: 133
    weight: 120
  },
  {
    imgSource: "/sushi/test3.png"
    ingredients: "Rice, Cream cheese, Sesame"
    name: "sushi3"
    price: 150
    weight: 100
  }
]

CodePudding user response:

There is no findLastIndex in JS

You can make a set

let  arr = [{
    imgSource: "/sushi/test2.png",
    ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce",
    name: "sushi1",
    price: 133,
    weight: 120
  },
  {
    imgSource: "/sushi/test2.png",
    ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce",
    name: "sushi1",
    price: 133,
    weight: 120
  },
  {
    imgSource: "/sushi/test3.png",
    ingredients: "Rice, Cream cheese, Sesame",
    name: "sushi3",
    price: 150,
    weight: 100
  }
]

const mySet = new Set()
arr.forEach(item => mySet.add(JSON.stringify(item)))
const newArr = Array.from(mySet).map(entry => JSON.parse(entry))

console.log(newArr)

CodePudding user response:

findLastIndex is not a js function, but I think what you are trying to do is something like this:

let arr = [
    {
        imgSource: "/sushi/test2.png",
        ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce",
        name: "sushi1",
        price: 133,
        weight: 120,
    },
    {
        imgSource: "/sushi/test2.png",
        ingredients: "Nori, Cucumber, Rice, Cream cheese, Sesame, Unagi sauce",
        name: "sushi1",
        price: 133,
        weight: 120,
    },
    {
        imgSource: "/sushi/test3.png",
        ingredients: "Rice, Cream cheese, Sesame",
        name: "sushi3",
        price: 150,
        weight: 100,
    },
];



let lastIndex = arr.lastIndexOf(arr.reverse().find(ele=>ele.name=="sushi1"))
console.log(lastIndex)

note that I used the reverse() function for find() because u need the last one.

extra note: these duplicate objects are not the same in == or === point of view, as the quality check operators for objects, check the references and not the actual value

  • Related