How can I filter an array containing a collection of strings and extract only specific columns?

How can I filter a dataset using another array of elements?

var filterBy = ["apple", "orange", "grapes"];
var selectColsIdx = [0, 1]

var data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]];

I am looking to apply the filterBy array as a filter to the subarrays in the data dataset (specifically index 1), and return only items indexed 0 and 1 as shown below:

res = [[1, "orange"], [3, "grapes"]]

Answer №1

You could utilize Array#flatMap along with a single iteration through the outer array.

const
    filterBy = ["apple", "orange", "grapes"],
    selectColsIdx = [0, 1],
    data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]],
    result = data.flatMap(a => filterBy.includes(a[1])
        ? [selectColsIdx.map(i => a[i])]
        : []
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

An alternate approach using two loops

const
    filterBy = ["apple", "orange", "grapes"],
    selectColsIdx = [0, 1],
    data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]],
    result = data
        .filter(a => filterBy.includes(a[1]))
        .map(a => selectColsIdx.map(i => a[i]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

It seems like you want to filter specific sub-arrays from a larger array and then extract only certain elements from each filtered sub-array.

You can achieve this by following the code snippet below:

const filterBy = ["apple", "orange", "grapes"]
const selectColsIdx = [0, 1]
const data = [[1, "orange", 20], [3, "grapes", 4], [6, "bananas", 9]]

// Utilizing Array.filter function to keep sub-arrays that meet the condition
// Using Array.some to check if any subitem satisfies the given callback
// Array.includes to determine if the item is included in the array
const output1 = data.filter(subArray => subArray.some(item => filterBy.includes(item)))

// Mapping the filtered sub-arrays to remain only selected columns based on index
const output2 = output1.map(subArray => subArray.filter((item, index) => selectColsIdx.includes(index)))

console.log("data:", data)
console.log("output1:", output1)
console.log("output2:", output2)
.as-console-wrapper { max-height: 100% !important; top: 0; }

Keep in mind that you can chain these array functions (filter and map) for more concise code.

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

Do you have any recommendations for exporting a PDF that includes one set of data but has two rows of headings?

I've encountered a challenge. I have been using jspdf with autotable to generate simple reports consisting of one row of headings and one body of data, which has worked flawlessly so far. My current setup involves Angular 8. However, I now need to c ...

What is the best way to remove the hover effect from a specific element within a div?

I am looking to achieve a specific hover effect where the white part does not darken when hovering over a certain element within its child elements. Here is the HTML code I have: <div className= {css.searchBarDiv}> <div className={css.searchBar ...

What is the best way to transform a collection of items into FormData?

In my current project, I have a JavaScript array structured as follows: var items = [{ ID: "1" count:'1', File: (binary file) }, { ID: "2" count:'2', File: (binary file) } ] My goal is to ...

Tips for creating a function to assign a CSS width using a JavaScript variable?

Here is the code snippet I have been working on: ...<script> function adjustElementSize() { var newSize = window.innerWidth - 600; document.getElementById("spin").style.width = newSize + "px"; document.getElementById("spin").style.height = newSize + ...

Discovering time overlaps with Javascript and moment.js

In my calendar project, I am storing events for a day in an array. The start and end times are stored as String values in the following format: Example of events in a day const events = [{ "_id": "5bdf91a78197f0ced6c03496", "user": "5bd62237d6 ...

Difficulty with parsing JSON in JavaScript and retrieving values by key

I'm encountering an error response within the ajax error function; $.ajax(Request).error(function (Response) { var content = JSON.stringify(Response.responseText); var obj = JSON.parse(content); console.log("Response.r ...

Steps to retrieve a roster of active users in SignalR

As someone new to SignalR, I was given my first task to create a simple chat app. After researching and experimenting, I successfully managed to set up a working chat page. My next step is to display a list of connected clients. Here is the code I wrote ...

JavaScript interprets a null date as January 1, 1970

My current setup involves using AngularJS to call a web API and store data. However, an issue arises when JavaScript interprets a null date as January 1st, 1970 in the input box. Is there a way to display an empty input box when the date is null? When rea ...

Dynamically change the state based on intricate layers of objects and arrays

Here is the issue I am facing I am attempting to update the state of an object named singleCarers I have the index of the roster in the rosters array that I need to update However, the key monday: needs to be dynamic, as well as the keys start: and fini ...

Can I connect a random HTML website to Node JavaScript?

Is it feasible to connect a random website with node.js? Can it be linked using just a URL, or is it necessary to have the file.html within the javascript directory? I am quite curious about this possibility as the html code does not belong to me and I am ...

What technique can be used to shift focus to the following text field after clicking a button

HTML : <input type="text" class="mytextbox"> <input type="text" class="mytextbox"> <input type="text" class="mytextbox"> <input type="text" class="mytextbox"> <input type="button" class="mybutton" value="focus next" onclick="f ...

Engaging with tasks like incorporating fresh elements into JavaScript code

I am looking to implement an event listener that triggers whenever a new element is added to the document or any of its children. Can someone recommend a method for accomplishing this? ...

Optimizing Performance with RequireJS Cache

We are currently experiencing an issue with RequireJS where it is not fetching a new version every time it is requested. We have attempted to address this by using the code below, but unfortunately, it has not solved the problem: require.config({ urlA ...

Leveraging the ASP.Net Ajax framework for seamless Xml manipulation across different browsers

Currently, I am in the process of updating a web application that utilizes ActiveX objects in client-side code to manipulate XML data. Unfortunately, this app is only compatible with Internet Explorer and I need to make it work across all browsers. I am s ...

Initiate animation on command with either Jquery or JavaScript

I have a special notification display box that showcases errors on my website .flash { height: 75px; position: fixed; top: 20px; right: 20px; z-index: 10; background-color: #ffffff; box-shadow: 0 0 30px 2px #dddddd; -webkit-animation: flas ...

Validation of OpenAPI requests on the client-side using React libraries

Is there a way to validate a request against a specific openAPI spec on the client side in a browser environment? I've spent countless hours searching and trying various openapi-tools, but all seem to be geared towards nodejs usage and not suitable f ...

The link function fails to execute

I have created a custom Directive. The issue I am facing is that the html template is not being rendered. Upon debugging, I noticed that the link function is never called because the instance function is also never called. To troubleshoot, I added "debu ...

When utilizing ReactJS onClick handler within a loop, it may only capture the last value of the index

When running the code provided below, handlePage consistently logs 30 instead of the expected index value i. This issue is not specific to ReactJS but rather a general JavaScript behavior. What could be causing this unexpected output and how can it be re ...

Stop React Form from automatically submitting by preventing automatic submission

I am currently facing an issue with a form that includes a rich text editor and a submit button. The problem arises when the style buttons in the rich text editor are clicked, causing the form inputs to submit unintentionally. My goal is to prevent this b ...

issue with bootstrap modals single firing when using remote data source

I am facing an issue with my table that contains a list of items, each item having a <select> element with different statuses. Here's how the process is supposed to work: Upon changing the status, a modal should pop up. The modal suc ...