1

let us consider an array

let array=["a","b","c","d","a"]

a is already present in the array, how to return true/false for this condition. i don't want to do this

let value=array.includes("a")

in this case i know a is repeated so i use includes("a"). How to write a generic solution to find if an item is repeated in an array .(imagine getting an array from an api, so u wont know what will be repeated )

  • you want to find whether an element is present in the array or to find whether it is repeated? – rsonx Aug 24 '20 at 09:33
  • You should really spend a few seconds searching on the internet: this question has been asked so many times before. – trincot Aug 24 '20 at 09:35
  • *"This question already has answers here: Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array"* Well I don't think the OP wants to get the non unique items of an array but instead he wants to get if an item is repeated or not, he has already said that he can get only whether the item is present in the array or not but couldn't get if it's repeated or not, please checkout my answer – Saadi Toumi Fouad Aug 24 '20 at 10:07

1 Answers1

0

Well you can use the .indexOf and .lastIndexOf to do that, so the idea is if both return the same index of the item then it's not repeated and it's unique but if the index is different then there are at least two copies of the item, so we can write a small function to do that given the array to search in and the item to search for

var x = [1, 6, 4, 6, 3, 2, 1];
function isRepeated(arr, n) {
  return arr.indexOf(n) !== arr.lastIndexOf(n);
}
console.log("1 is repeated? " + isRepeated(x, 1));
console.log("3 is repeated? " + isRepeated(x, 3));
console.log("6 is repeated? " + isRepeated(x, 6));
console.log("4 is repeated? " + isRepeated(x, 4));
Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18