Refining a nested array by a selected index with numerous potential values

Consider the scenario of having 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"]
];

We also have a small array containing string values. This is just a simplified example, there could be more values:

var string_values = ["0.1", 4.2"]

The objective here is to filter or parse the array in such a way that we only get the subarrays where the value at index 1 matches any of the string_values. The current approach works but is somewhat cumbersome. Is there a more efficient method using .filter or .find (or any other single line technique) 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);

Answer №1

Perhaps something along the lines of:

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

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

const result = data_array.filter(([_, value]) => search_values.includes(value));

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

If search_values grows in size, it might be beneficial to utilize a Set object (MDN, performance blog post):

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

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

const result = data_array.filter(({ 1: value }) => search_values.has(value));

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

(The use of destructuring with value in the second example is not directly related to Set operation, but I occasionally find it convenient while working with arrays.)

Answer №2

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

let valuesToFilter = ["0.1", "4.2"];
let filteredData = data.filter(item => valuesToFilter.includes(item[1]));

console.log(filteredData)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve the request body in Node.js Express server-side code in order to receive an array passed from the front end

I am facing an issue where I need to save a user's array to mongo. When the data passes through the bridge and reaches the posts, it appears as a strange object with string versions of its indices. I am attempting to convert it back into a normal arra ...

Is it possible to customize the MongoDB Collection before loading the web application by fetching data asynchronously using Promises?

I am currently working with MongoDB and NodeJS, trying to preload my Collection customers every time the site is loaded. The process involves emptying the collection, populating it with empty Documents, and then replacing them with real data fetched from a ...

Leveraging the power of fullpage.js to activate Velocity.js/Blast.js animations

Referencing a solution shared on this forum: Velocity.js/Blast.js starting opacity at 0 I am currently working with Velocity.js and Blast.js to implement a basic word-by-word loading animation, commonly used. This setup also involves Cycle2. Additionally, ...

Null value arising due to AJAX's asynchronous nature

I am facing an issue with a form that includes a select option displaying various choices. My goal is to retrieve the selected option and display it in a text box. The options are loaded using AJAX from an XML data source. When attempting to grab the sele ...

Cannot find property in type, and the parameter is implicitly of an unspecified type

I've been encountering this issue where I keep getting an error message. I attempted to resolve it by setting "noImplicitAny": false in tsconfig.json, but unfortunately that did not work. As for the 'Property does not exist on type' error, I ...

Can someone please direct me to the source code for the @mediapipe/camera_utils npm module?

The MediaPipe project's source code can be found on this GitHub repository To utilize MediaPipe with JavaScript in your browser, check out the guide at MediaPipe in JavaScript When working with MediaPipe and JavaScript, you will need to incorporate ...

Is it possible for npm packages to include a variety of programming languages?

Let's say you are looking to release an npm package containing bash scripts for specific tasks. Would this be permitted on the npm package registry? Additionally, is there a method to run a bash script within the code of a particular javascript file? ...

Calculate the pixel distance between various divs by measuring the horizontal distance from the left border to the right

I am trying to find the precise distance between : #main div left edge to the first div with class="b" between the first div with class="b" to the second div with class="b" It's worth noting that the divs may be arranged randomly and could have fix ...

Citation in HTML and CSS

How can I reference a specific folder/file in my HTML code so that it encompasses the CSS, JavaScript, and HTML files? Here's an example of the code I am working with: <input onclick="setTimeout(function(){location.href='Darkmode&ap ...

Gather data from a variety of HTML5 video seminars

I am encountering an issue where I have multiple videos and I want to receive events from each of them. However, I am only able to get the event from one video (as tested in Chrome). Why is this happening? Here is the HTML code: <video id="video1" pre ...

Tips on creating a universal shortcut function for React.js components using decorators

Utilizing React Intl for internationalization requires me to utilize this.props.intl.formatMessage({id: 'some.message.id'}, values) to retrieve a translated string within the render() method. Is there a way to create a decorator that acts as a sh ...

Tips on implementing two ng-repeat directives within a specific element

Inside a JSON file, there is an array that needs to be iterated within <td> tags. The functionality entails creating a table based on user input, which includes the number of rows, input columns, and output columns provided by the user. Three arrays ...

Searching for data in Ag grid Vue using a filter

Can someone help me create a search filter in ag grid vue like the one shown in this image? Image link: https://ibb.co/cwVq7DD For documentation, refer to: https://www.ag-grid.com/vue-data-grid/tool-panel-columns/#read-only-functions I attempted to impleme ...

Feeling unsure about the concepts of scoping and the "this"

Recently, I came across a code snippet at this source: : var CounterButton = function(el){ this.$el = $(el); this.counter = 0; this.bindEvents(); this.myVal = 1; } CounterButton.prototype.bindEvents = function(){ this.$el.click(this. ...

Learn the best way to retrieve the highest number from a Array<String> in TypeScript or JavaScript

Can someone help me create a function in JS or TS that meets the following requirements? I am looking for a functional programming approach. ・Input type: Array(String) ・Output type: string or undefined Examples Input Result ["" ...

How can I transform any object (such as an array) into JSON format and retrieve it as a string? Specifically in the context of Android

Is there a method to convert any type of object, like an array, into JSON and retrieve it in string format? Here's an example: public String jsonEncode(Object obj) { return jsonString; } ...

Sending an XMLHttpRequest in PHP causes a blank array to be returned

> xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var jsondata = xmlhttp.responseText; console.log(xmlhttp.responseText); document.getElementById("jsondata").value = js ...

Is there a way to retrieve a list of functions using ScriptEngine in Java?

I am using Jsoup to extract the JavaScript portion of an HTML file and store it as a Java String object. Furthermore, I am looking to extract lists of functions and variables within the JavaScript functions using javax.script.ScriptEngine. The JavaScript ...

Exploring the functionality of adding a table by clicking on each column in Highcharts using Reactjs

Utilizing highcharts-react-official for highcharts implementation, I have successfully displayed a column graph. However, the requirement now is to show a table containing detailed information related to each clicked column, including hyperlinks. I am stru ...

Experience the power of AngularJS and jQuery in crafting a dynamic, scalable table with the ability to

I am attempting to create an expandable table using JQuery, and I found a helpful resource at . However, I have encountered a conflict between angularjs and jquery. Here is the snippet of my HTML file: <table> <tbody ng-repeat="row in constru ...