-5

Let's say we have an array: let arr = [10,10,5,11,5]

How could I check for all the numbers that are equal? ( basically duplicates )

What i thought of is a forEach and compare every number but that's not very optimal. A filter ? Maybe. Anyone has any good ideea that would be optimal?

Chris D
  • 195
  • 1
  • 1
  • 8
  • What do you mean by "all the numbers that are equal"? You want the unique numbers in the array? You want to know if they're *all* equal? Or...? – Dave Newton Mar 05 '19 at 22:19
  • What is your desired output? An array without any duplicate elements? – 4castle Mar 05 '19 at 22:19
  • I'm not sure who's downvoting all the answers, but it's non-sensical: the problem statement isn't sufficient--if anything the question should be downvoted. – Dave Newton Mar 05 '19 at 22:20
  • @ChrisD A `filter` also iterates and runs a comparison. You need to be more specific with your problem statement. – Dave Newton Mar 05 '19 at 22:21
  • Check this: https://stackoverflow.com/a/38206980/2050306 – robert Mar 05 '19 at 22:23

4 Answers4

0

You can use reduce to build down the values you need

let arr = [10, 10, 5, 11, 5];

let duplicates = getDuplicates(arr);

console.log(duplicates);

function getDuplicates(arr) {
  let duplicates = arr.reduce((acc, item) => {
    if(acc[item] !== undefined) {
      acc[item] = true;
    } else {
      acc[item] = false;
    }
    return acc;
  }, {});
  
  return Object.keys(duplicates).filter(item => duplicates[item]);
}
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
0

You can use filter

let arr = [10,10,5,11,5];

const duplicates = array => array.filter((item, index) => array.some((i, idx) => i === item && idx < index));

console.log(duplicates(arr));

or reduce

let arr = [10,10,5,11,5];

const duplicates = array => array.reduce((results, item, index) => {
  if (!results.some(i => i === item) && array.some((i, idx) => i === item && index !== idx)) {
    results.push(item);
  }
  return results;
}, []);

console.log(duplicates(arr));
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
-1

You can use a Set to remove the duplicates and then compare the lengths of the two arrays.

let arr1 = [10,10,5,11,5]
let arr2 = [10,11,5]

function hasDuplicates(arr) {
  return arr.length != [...new Set(arr)].length
}

console.log(hasDuplicates(arr1))
console.log(hasDuplicates(arr2))
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
-1

Really quick with every

let arr = [10,10,5,11,5]
//arr = [10,10,10,10]
if (arr.every( v => v === arr[0] )) {
  console.log("yes")
} else {
  console.log("no")
}

Or using Lodash

let arr = [10,10,5,11,5]
//arr = [10,10,10,10]
if (_.uniq(arr).length == 1) {
  console.log("yes")
} else {
  console.log("no")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
Arthur
  • 4,870
  • 3
  • 32
  • 57