Remove Duplicates
Problem:- write a programme that removes duplicate items from the cart or list array containing objects.
Divide the problem into small Steps: -
create an array of a list of items with duplicate item names.
apply a filter on the cart and remove items that already exist in the array
store the remaining items into a new array and log into the console.
Applying the steps:-
create an array of a list of items with duplicate item names.
-> Here we are making an array called a cart and the cart contained objects of fruit name and their price. also include some duplicate items for removal into the cart
const cart = [ { fruit: "apple", price: 100, }, { fruit: "banana", price: 30, }, { fruit: "orange", price: 80, }, { fruit: "apple", price: 100, }, { fruit: "pear", price: 50, }, { fruit: "guava", price: 60, }, { fruit: "pear", price: 50, }, ]
apply a filter on the cart and remove items that already exist in the array
-> Declare a new variable called newArray and assign an empty array
const newAreay = []
declare another variable uniqueCart, In this variable apply a filter on a cart and pass one parameter.
const uniqueCart = cart.filter( (e) => { }
in the filter, we check whether fruit names are already available or not. if not available then push the fruit name into newArray.
if the fruit name already exists in the newArray then we return false. so this item will also remove from the filter.
const cartInclude = newCart.includes(e.fruit) if (cartInclude) { return false } else { newCart.push(e.fruit); return true }
for the check, when the first fruit 'apple' pass from the filter that is not included in the newArray. so 'apple' is stored in newArray. when the apple comes again into the filter at that time the 'apple' already exists in newArray. so the condition returns false and the item is not stored again into newArray and removed from the filter or unique art also.
store the remaining items into a new array and log into the console.
-> Finally we get the unique item into uniqurCart and all the duplicate items are removed using the filter. now console the uniqueCart using console.log()
const newCart = []
const uniqueCart = cart.filter((e) => {
const cartInclude = newCart.includes(e.fruit)
if(cartInclude) {
return false
} else {
newCart.push(e.fruit)
return true
}
});
console.log(uniqueCart)