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", }, ...........]
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)] }
I setup getEmotionsArray(cats) function
-
I set and empty array
emotionsArray. -
I use
for ofmethod to loop thru the cats data and then pushemotionTagsarray intoemotionsArray.
[["moody"], ["moody", "insomniac"], ["moody"], ["confused", "sad"],.....]
- The
emotionsArraywill have array of array.
["moody", "moody", "insomniac", "moody", "confused", "sad",...]
- Then I use
Array.prototype.flat()method to flattenemotionsArray.
["moody", "insomniac", "confused", "sad", "dominant", "happy", "relaxed", "hungry", "scared"]
- To get the unique values in the array simply use
[...new Set(flattenArr)].
Eat, sleep, code, repeat!
Andrew Tan