Comparing a value of objects array with string - returning boolean

Viewed 149

localStorage.getItem("test") - is holding some string value

I want to compare this value with array of objects - each of them stringified

If one of items in this array (newCombination) is the same as localStorage.getItem("test"), I want to return false.

It's not working, it's returning sometimes true, sometimes false. I hope it doesn't loop through whole array and stops if it's not true. I want it to loop though everything until it doesn't compare and it returns false - or true if it doesn't match anywhere.

function checkDuplicity(){
  for (var i = 0; i < newCombination.length; i++) {
    if(JSON.stringify(newCombination[i]) == localStorage.getItem("test")){
      return false
    }else{
      return true
    }
  }
}

Example of what is in array of objects on positions 0-3 (from DevTool):

0: {movie: "Movie A", date: "2021-01-13", time: "10:00 am"}
1: {movie: "Movie A", date: "2021-01-14", time: "10:00 am"}
2: {movie: "Movie B", date: "2021-01-14", time: "10:00 am"}
3: {movie: "Movie C", date: "2021-01-14", time: "10:00 am"}
length: 4
__proto__: Array(0)

1 Answers

You should only return true at the end, after you have checked every item in the array. Otherwise, the function always finishes after the first iteration.

function checkDuplicity(){
  for (var i = 0; i < newCombination.length; i++) {
    if(JSON.stringify(newCombination[i]) == localStorage.getItem("test")){
      return false
    }
  }
  return true;
}

You can also use Array#every or Array#some for this.

function checkDuplicity(){
  return newCombination.every(x => JSON.stringify(x) != localStorage.getItem("test"));
}
Related