简体   繁体   English

如何使用 JavaScript 中的索引过滤 arrays 数组?

[英]How do I filter through an array of arrays using an index in JavaScript?

Im'm working on a JavaScript side prokect and I've got a json file with an array with arrays like this:我正在研究 JavaScript 侧面项目,我有一个 json 文件,其中包含一个带有 arrays 的数组,如下所示:

arr = 

{
  "values": [
    ["Form Factor", "OS"],
    ["Landscape", "Android 9\n(Source)"],
    ["Portrait", "Analogue OS"],
    ["Micro\nLandscape", "?"]
  ]
}

The first array with "Form factor" (index 0) are the headlines.第一个带有“Form factor”(索引 0)的数组是标题。 If I want to get all the "form factors" from the arrays how would I do that?如果我想从 arrays 获得所有“外形尺寸”,我该怎么做?

I know that "Form Factor" has index 0 but how do i filter through several arrays at once with an index?我知道“Form Factor”的索引为 0,但我如何使用索引一次过滤多个 arrays? in the end I want an array like最后我想要一个像

results = ["Form Factor", "Landscape", "Portrait", "Micro\nLandscape"]

I tried it like this:我试过这样:

const index = 0;
const result = this.arr.values.filter(function (eachElem) {
        return eachElem == index;
      });

But that just gives me back an empty array.但这只是给了我一个空数组。

Don't forget to check this不要忘记检查这个

arr.values.map(x => x[0])

Your code isn't working because a) index isn't defined, you need to also put it as a parameter and b) in your case no element will be true.您的代码无法正常工作,因为 a) 未定义索引,您还需要将其作为参数,并且 b) 在您的情况下,没有任何元素为真。 I would use a traditional for loop in your case but surely if you want you can do it with es6 magic.在你的情况下,我会使用传统的 for 循环,但如果你愿意,你可以使用 es6 魔法来做到这一点。

let result = [];
for (let i = 0; i < arr.values.length; i++) {
    result.push(arr.values[i][0]);
}
console.log(result);

Just use array.find() it's much easier and you can search for your element in your array:只需使用 array.find() 它就容易多了,您可以在数组中搜索您的元素:

const found = array1.find(element => element > 10); const found = array1.find(element => element > 10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM