DEV Community

anderu
anderu

Posted on • Edited on

The easy way to get unique values in array of array Javascript

const catsData = [
    {
        emotionTags: ["moody"],
        isGif: false,
        image: "angry.jpeg",
        alt: "A cat looking moody",
    },
    {
        emotionTags: ["moody", "insomniac"],
        isGif: false,
        image: "angry2.jpeg",
        alt: "A cat looking moody",
    },
    ...........]
Enter fullscreen mode Exit fullscreen mode

Today I learn an easy method to get unique values in array of array. The catsData above show there is an array of object and i want to get the object.emotionTags data.

function getEmotionsArray(cats){
    const emotionsArray = [];
    for (let cat of cats) {
       emotionsArray.push(cat.emotionTags)
    }
    let flattenArr = emotionsArray.flat()
    return [...new Set(flattenArr)]
}
Enter fullscreen mode Exit fullscreen mode

I setup getEmotionsArray(cats) function

  • I set and empty array emotionsArray.

  • I use for of method to loop thru the cats data and then push emotionTags array into emotionsArray.

[["moody"], ["moody", "insomniac"], ["moody"], ["confused", "sad"],.....]
Enter fullscreen mode Exit fullscreen mode
  • The emotionsArray will have array of array.
["moody", "moody", "insomniac", "moody", "confused", "sad",...]
Enter fullscreen mode Exit fullscreen mode
  • Then I use Array.prototype.flat() method to flatten emotionsArray.
["moody", "insomniac", "confused", "sad", "dominant", "happy", "relaxed", "hungry", "scared"]
Enter fullscreen mode Exit fullscreen mode
  • To get the unique values in the array simply use [...new Set(flattenArr)].

Eat, sleep, code, repeat!
Andrew Tan

Top comments (2)

Collapse
 
lionelrowe profile image
lionel-rowe

Looks like a perfect use case for flatMap:

The flatMap() method of Array instances returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level. It is identical to a map() followed by a flat() of depth 1 (arr.map(...args).flat()), but slightly more efficient than calling those two methods separately.

Then you can write it in just 1 line:

const emotions = [...new Set(catsData.flatMap((cat) => cat.emotionTags))]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
anderutan profile image
anderu

Hi @lionelrowe, thanks for your comment!