2

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)

2
  • Can you please share the newCombination array values/example? Commented Jan 13, 2021 at 19:18
  • Just edited the post with example, if its enough like that :) Commented Jan 13, 2021 at 19:45

1 Answer 1

2

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"));
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh.. I see.. Thank you very much
@DrCharisma No problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.