I'm trying to prevent an object getting added to an array more than once if it already exists. From what I gather online, I can use the indexOf
of method to compare a value, but in my test, items still get added to my array regardless of whether they exist?
What am I doing wrong?
function getRndInteger(min = 1, max = 5, step = 1) {
const range = (max - min) / step
return Math.floor(Math.random() * range) * step + min
}
const items = []
let obj = {
content: "<p></p>"
}
setInterval(() => {
const random = getRndInteger(1, 3)
obj = {
content: `<p>hello world ${random}</p>`
}
if (items.indexOf(obj.content) === -1) items.push(obj)
console.log(items)
}, 1000)
If an item in my array has another item with exactly the same content, then I want to prevent adding it again, why doesn't this work?
Here's a JS fiddle as well -> https://jsfiddle.net/mxLcyjo8/1/
Thanks!
hello world 1
`, which isn't right. I need to exclude duplicate objects form my array – Ryan H Mar 30 '21 at 12:45