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.
I have already tried to use myArr.lastIndexOf(myArr.find((item) => item.name == itemName)); but it doesnt work.
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
}
]
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
I have finally found solution for my answer, thanks to Mohamad ali ghorbani, I managed to find right way to do it.
Here is how i got my last Index:
const nameArray = myCart.map((item) => item.name);
const indexOfItem = nameArray.lastIndexOf(itemName);
myCart.splice(indexOfItem, 1);
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)