I have an array in javascript which contains a number of nested arrays
let data = [
["Apple","Fruit","Red"],
["Pear","Fruit","Green"],
["Orange","Fruit","Orange"],
["Carrot","Vegetable","Orange"],
["Pea","Vegetable","Green"],
["Pumpkin","Vegetable","Orange"]
]
From this array, I wish to create two new arrays. Arr1 is the unique food types (index2) and Arr2is the unique colors (Index 3).
My new arrays should be:
Arr1 = ["Fruit","Vegetable"]
Arr2 = ["Red","Green","Orange"]
I have managed to achieve this by using for each, where I've pushed every second object to an array. I then filter this new array for unique values. This is the code I'm using to do this:
var Foods = []
var Colors = []
for (var key in data) {
Foods.push(data[key][1]);
}
for (var key in data) {
Colors.push(data[key][2]);
}
let Arr1 = [...new Set(Foods)]
let Arr2 = [...new Set(Colors)]
console.log(Arr1)
console.log(Arr2)
Although this works well, as a javascript beginner, I thought there may be a more elegant way to achieve.
For example is it not possible to filter all the unique values of data with an index of [2]?