Categories
JavaScript Answers

How to Get All Non-Unique Values in a JavaScript Array?

Spread the love

Array.prototype.filter

We can use the JavaScript array’s filter method to return an array that meets the given condition.

It takes a callback that returns the condition we want each returned item to have.

So we can combine this with calling the indexOf method in the callback to check whether the item is the first instance of an item.

To do this, we call indexOf on the array that filter is called on, which we can get from the 3rd parameter of the callback.

Then we can check whether the returned index is the same one that the item being iterated through is in.

For instance, we can write:

const duplicates = [1, 2, 2, 4, 3, 4].filter((e, index, arr) => arr.indexOf(e) !== index)
console.log(duplicates)

Then we call filter with a callback that takes the e , index , and arr parameters.

e is the item being iterated through.

index is the index of item e .

And arr is the array that filter is being called on.

We call indexOf on arr with argument e to return the index of the first instance of e in arr .

And if it’s not the same as index , then we know it’s not the first instance of a value.

Therefore, duplicates is [2, 4] since they’re duplicated in the array.

Count the Items

We can count the items in an array by creating our own object to set the count.

For instance, we can write:

const obj = [1, 2, 2, 4, 3, 4]
  .map((val) => {
    return {
      count: 1,
      val
    }
  })
  .reduce((a, b) => {
    a[b.val] = (a[b.val] || 0) + b.count
    return a
  }, {})

const duplicates = Object.entries(obj)
  .filter(([, val]) => {
    return val > 1
  })
  .map(([key]) => +key)
console.log(duplicates)

We call map to map each entry to an object with the count set to 1 and the val with the array item value.

Then we call reduce to create an object with the count of each item, with each item being the key.

We do this by assigning the count from a[b.val] with (a[b.val] || 0) + b.count .

b.count has the new count.

And we return a which has all the counts tallied so far.

The 2nd argument is an empty object so we create an object at the end.

Then to get the duplicate values, we get all the keys with value being bigger than 1.

To do this, we call Object.entries on obj .

Then we call filter with a callback to return any entry with val bigger than 1.

val is the object property value.

Then we call map to get the key from the key-value pair arrays.

So we get the same result as in the previous example for duplicates .

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *