Reputation: 419
I have an array of arrays of data returning to me back from a csv file. I am attempting to filter out each index of an array depending on which title is in the array. For example:
If an index of the array has the name "Retail" return that entire index which includes some values.
Here is my array :
[
[
"Retail",
"22,477",
"24,549",
"19,580",
"15,358",
],
[
"Online",
"8,653",
"7,586",
"2,432",
"4,321"
],
[
"In Store",
"2,532",
"2,836",
"5,632",
"7,325"
]
]
I've attempted these two separate ways and both are returning an array of 0:
filtArr = dataList.filter(name => name.includes('Retail')) //expecting the array length 5 with "Retail" and it's values
attempt 2
filtArr = dataList.filter(function (name) {
return (name === "Retail")
})
Expected return is: console.log(filtArr) // [ 0. "Retail", 1. "22,477", 2. "24,549", 3. "19,580", 4. "15,358"
Upvotes: 1
Views: 3192
Reputation: 93
A good way to check if an array contains some item is to test it with the indexOf method. It will return -1 if the item is not found or else its index.
You could do this to store all arrays containing 'Retail' in them:
let retailArrays = [];
arrayOfArrays.forEach(
array => {
if( array.indexOf('Retail') !== -1) {
retailArrays.push(array);
};
}
)
Upvotes: 2
Reputation: 781004
You apparently have trailing spaces after some of the names, so maybe "Retail"
is actually "Retail "
.
It also looks like the name is always the first element of the nested array, so there's no need to search the whole array.
So use trim()
on the first element to remove the surrounding spaces.
filtArr = dataList.filter(arr => arr[0].trim() == 'Retail');
var dataList = [
[
"Retail",
"22,477",
"24,549",
"19,580",
"15,358",
],
[
"Online",
"8,653",
"7,586",
"2,432",
"4,321"
],
[
"In Store",
"2,532",
"2,836",
"5,632",
"7,325"
]
];
filtArr = dataList.filter(arr => arr[0].trim() == 'Retail');
console.log(filtArr);
Upvotes: 1