Home > Enterprise >  how can i stop duplicate array in Javascript?
how can i stop duplicate array in Javascript?

Time:10-11

This is a function that adds data and stores it in local storage. how do i stop it from storing duplicate data

const WishlistHandler = (video, id) => {
        console.log({ video })
        console.log({ id })
        let mylist = ls('list')
        let itemGet;
        let a = video
        if (mylist !== null) {
          itemGet = ls.get('list')
    
          if (!itemGet.includes(video)) {
            itemGet.push(video)
            ls.set('list', itemGet)
            SetWishList(itemGet)
          }
    
    
        } else {
          console.log("not same")
          ls.set('list', [video])
        }
    
      }

CodePudding user response:

Depending on the type of your array element you can do this a couple of ways:

A primitive value

const data = [1,2,3,4,5,6,7,8,9,10]
const addDataIfNotPresent = (arr,val) => arr.includes(val) ? arr : [...arr, val]

console.log(addDataIfNotPresent(data,5))
console.log(addDataIfNotPresent(data,0))
console.log(addDataIfNotPresent(data,1))
console.log(addDataIfNotPresent(data,2))
console.log(addDataIfNotPresent(data,11))
console.log(addDataIfNotPresent(data,-1))

An object

const data = [
 {id: 1, value: '1'},
 {id: 2, value: '2'},
 {id: 3, value: '3'},
 {id: 4, value: '4'},
 {id: 5, value: '5'},
 {id: 6, value: '6'},
 {id: 7, value: '7'},
 {id: 8, value: '8'},
]

const addDataIfNotPresent = (arr, obj) => arr.find(el => el.id === obj.id) ? arr : [...arr, obj]

console.log(addDataIfNotPresent(data, {id: 2, value: '2'}))
console.log(addDataIfNotPresent(data, {id: 3, value: '3'}))
console.log(addDataIfNotPresent(data, {id: 4, value: '4'}))
console.log(addDataIfNotPresent(data, {id: 10, value: '10'}))
console.log(addDataIfNotPresent(data, {id: 11, value: '11'}))

CodePudding user response:

It will depend on what makes your entry unique, let's say you have an objects {'1' : "panda.mp4", '2' : "monkey.mp4"} and you want to make sure that adding ('panda.mp4', '1'). won't work, this code can help you.

In this case, I consider the id as the element that makes the entry unique. Based on this, you can customize and make it work as you need.

const WishlistHandler = (video, id) => {
        let mylist = JSON.parse(localStorage.getItem('list'))
        if (mylist !== null) {
    
          if (!Object.keys(mylist).includes(id)) {
            localStorage.setItem('list', JSON.stringify({...mylist, [id]: video}))
          }
    
    
        } else {
          localStorage.setItem('list', JSON.stringify({[id]: video}))
        }
      }
  • Related