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 of
method to loop thru the cats data and then pushemotionTags
array intoemotionsArray
.
[["moody"], ["moody", "insomniac"], ["moody"], ["confused", "sad"],.....]
- The
emotionsArray
will 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
Top comments (2)
Looks like a perfect use case for
flatMap
:Then you can write it in just 1 line:
Hi @lionelrowe, thanks for your comment!