-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?

5
  • 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...? Commented Mar 5, 2019 at 22:19
  • What is your desired output? An array without any duplicate elements? Commented Mar 5, 2019 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. Commented Mar 5, 2019 at 22:20
  • @ChrisD A filter also iterates and runs a comparison. You need to be more specific with your problem statement. Commented Mar 5, 2019 at 22:21
  • Check this: stackoverflow.com/a/38206980/2050306 Commented Mar 5, 2019 at 22:23

4 Answers 4

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]); }

Sign up to request clarification or add additional context in comments.

Comments

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));

Comments

-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))

Comments

-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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.