0

Lets say I have a nested array:

var test_array = [
 ["0", "0.1", "4.2", "Kramer Street"],
 ["1", "0.2", "3.5", "Lamar Avenue"],
 ["3", "4.2", "7.1", "Kramer Street"]
];

I also have a small array of string values. This is a simplified example as there could be a single value or multiple values:

var string_values = ["0.1", 4.2"]

I want to filter or parse the array to just get the subarrays where index 1 and only index 1 is equal to either of my string_values. I've tried the following approach but its cumbersome (although it works). Is there a better way using .filter or .find (or another single line method) to achieve this?

var test_array = [
     ["0", "0.1", "4.2", "Kramer Street"],
     ["1", "0.2", "3.5", "Lamar Avenue"],
     ["3", "4.2", "7.1", "Kramer Street"]
    ];

var string_values = ["0.1", "4.2"]
var new_array = [];

for (let i=0; i < test_array.length; i++) { 
    if (string_values.indexOf(test_array[i][1]) !== -1) { 
        new_array.push(test_array[i]); 
    } 
}

console.log(new_array);

2 Answers 2

1

Maybe something like:

const test_array = [
  ["0", "0.1", "4.2", "Kramer Street"],
  ["1", "0.2", "3.5", "Lamar Avenue"],
  ["3", "4.2", "7.1", "Kramer Street"]
];

const string_values = ["0.1", "4.2"];

const res = test_array.filter(([_, v]) => string_values.includes(v));

console.log(JSON.stringify(res));

In case string_values could get significantly larger it might be worth using Set (MDN, blog post on performance) :

const test_array = [
  ["0", "0.1", "4.2", "Kramer Street"],
  ["1", "0.2", "3.5", "Lamar Avenue"],
  ["3", "4.2", "7.1", "Kramer Street"]
];

const string_values = new Set(["0.1", "4.2"]);

const res = test_array.filter(({ 1: v }) => string_values.has(v));

console.log(JSON.stringify(res));

(The way I got v differently in the second example is irrelevant to the use of Set, I just find myself suddenly remembering that you can destructure arrays like that occasionally.)

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, both of these solutions are great, but I chose this one because of the application of Set() which might help in the more complex situations. My example is a very simplified illustration of the actual arrays.
1

var test_array = [
     ["0", "0.1", "4.2", "Kramer Street"],
     ["1", "0.2", "3.5", "Lamar Avenue"],
     ["3", "4.2", "7.1", "Kramer Street"]
    ];

var string_values = ["0.1", "4.2"]
var new_array = test_array.filter(obj=> string_values.find(num=> num === obj[1]))

console.log(new_array)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.