2

I have an array for example

var a = [1,4,6,1,1,1,1];

and I need to compare each element in array for similarity. If all of them are similar I need return true, if one or more of them are different it should return false

Will be glad to get the answer.

Vasyl Kozhushko
  • 83
  • 3
  • 11

3 Answers3

1

Here's one method to achieve it, by using Set.

var a = [1,1,1,1];
var b = [1,2,3,4,5,1,2,3];

function check(arr) {
  console.log([...new Set(arr)].length == 1 ? true : false);
}

check(a);
check(b);
kind user
  • 40,029
  • 7
  • 67
  • 77
1

if they all need to be the same then you could just check to see if everything in the array is equal to the first element by using filter and length. The length of the array filtered by any element in the list should equal the original length.

const a = [1, 4, 1, 1, 1, 1, 1];

function similarity(arr) {

  let firstItem = arr[0];

  return arr.filter(elements => elements == firstItem).length != arr.length ? false : true;
}


console.log(similarity(a));
Jonathan Portorreal
  • 2,730
  • 4
  • 21
  • 38
0

You can make use of the every Method.

From MDN

The every() method tests whether all elements in the array pass the test implemented by the provided function.

var notsimilar= [1,4,6,1,1,1,1];
var similar= [2,2,2];
console.log(notsimilar.every((x,i,a) => a[i] === a[0]));
console.log(similar.every((x,i,a) => a[i] === a[0]));
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41