JavaScript-过滤字符串数组 [英] JavaScript - Filtering an array of strings
问题描述
我有一个从csv文件返回的数据数组。我试图根据数组中的标题来过滤出数组的每个索引。例如:
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.
这是我的数组:
[
[
"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"
]
]
我尝试过这两种方式都返回0数组:
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
attempt 2
filtArr = dataList.filter(function (name) {
return (name === "Retail")
})
预期收益为: console.log(filtArr)// [0.零售,1. 22,477,2. 24,549,3. 19,580,4. 15,358
推荐答案
检查数组是否包含某些项目的一种好方法是使用indexOf方法对其进行测试。
如果找不到该项目或其索引,它将返回-1。
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);
};
}
)
这篇关于JavaScript-过滤字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!