Home > Back-end >  How do I filter through an array of arrays using an index in JavaScript?
How do I filter through an array of arrays using an index in JavaScript?

Time:12-11

Im'm working on a JavaScript side prokect and I've got a json file with an array with arrays like this:

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. If I want to get all the "form factors" from the arrays how would I do that?

I know that "Form Factor" has index 0 but how do i filter through several arrays at once with an index? 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.

CodePudding user response:

Don't forget to check this

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

CodePudding user response:

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. I would use a traditional for loop in your case but surely if you want you can do it with es6 magic.

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

CodePudding user response:

Just use array.find() it's much easier and you can search for your element in your array:

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

  • Related