Filter an array based on the values stored in another array

I have an array

sourceArray = [{'type':'A'}, {'type':'B'}, {'type':'C'}, {'type':'D'}];
arrayB  = ['B', 'C'];

I am looking to filter out elements in sourceArray that are also present in arrayB. Rather than iterating through arrayB, I am seeking a more efficient solution.

filteredArray = [];
for(x in arrayB)
{
filteredArray.concat( sourceArray.filter(function(e1){ return e1.type == arrayB[x])} );
}

Is there a more elegant approach to achieve this?

Answer №1

To solve this, you can use the `.filter` method:

sourceArray = [{'type':'A'}, {'type':'B'}, {'type':'C'}, {'type':'D'}];
arrayB  = ['B', 'C'];

result = sourceArray.filter(function(item) {
  return arrayB.indexOf(item.type) >= 0;
});

document.write("<pre>" + JSON.stringify(result,0,3));

[].filter(func) is a function that goes through an array and collects elements for which the provided `func` returns `true`. In our case, we are checking if the `arrayB` contains the `item.type` and returning `true` if it does (refer to indexOf).

If you prefer an ES6 solution:

sourceArray = [{'type':'A'}, {'type':'B'}, {'type':'C'}, {'type':'D'}];
arrayB  = ['B', 'C'];

setB = new Set(arrayB)
result = sourceArray.filter(item => setB.has(item.type))

Answer №2

One method to address this issue is by utilizing the concept of filtering in conjunction with the indexOf function. However, it's important to note that this approach involves a hidden iteration process which can become expensive when dealing with larger arrays within your arrayB.

For a more efficient solution in most scenarios, consider constructing a hash map of elements to facilitate quicker filtering operations. An example implementation could look like the following:

var filteredArray = sourceArray.filter(
    function(v){ return this[v.type] }.bind(arrayB.reduce(
        function(s,v){ s[v]=1; return s }, Object.create(null)
    ))
)

Within this code snippet,

arrayB.reduce(function(s,v){ s[v]=1; return s }, {}))
generates an object where the keys represent valid types: {B: 1, C: 1}. Retrieving properties from such an object is typically efficient due to the performance capabilities of JavaScript engines.

Answer №3

var sourceArray = [{
    'type': 'A'
}, {
    'type': 'B'
}, {
    'type': 'C'
}, {
    'type': 'D'
}];
var arrayB = ['B', 'C'];

var filteredArray = sourceArray.filter(function (value) {
    for (var index = 0; index <= arrayB.length; ++index) {
        if (value.type == arrayB[index]){
            return value;
        }
    }
});
alert(JSON.stringify(filteredArray));

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

Is it possible for a chrome extension to allow only specific third-party cookies and storage to be

My Chrome extension inserts an iframe from foo.com into bar.com, creating a situation where bar.com now includes a foo.com iframe. However, I have observed that this iframe encounters difficulties when attempting to write to localStorage if the user has ...

Obtain access to a React DOM Element using an external script

I am facing a challenge in accessing a React DOM element 'id' from an external script file. It seems like the script is properly imported because console.log('test') from the file is working; however, console.log(myDiv) returns null. I ...

Ensuring that the form button is reset automatically upon using the browser's "Back" button

Even after exploring numerous similar questions and trying out various suggested solutions, I still can't seem to get anything to work. The issue I'm facing involves a form on a webpage. To combat the problem of impatient individuals clicking &a ...

Interactive tooltip with hyperlinks powered by jQuery

Is it possible to create a pop-up window with links that behave like a normal tooltip but can be clicked on by the mouse? How can this functionality be achieved without losing focus when hovering over the links causing the window to close? jQuery(docume ...

Issue with showing the information on the table

Currently, I am working on a basic JavaScript program that requires me to collect five personal details from the user: their name, address, city, gender, and age. The goal is to display these details in a table format, but unfortunately, the program is not ...

What is the reason for the malfunction of this JavaScript code designed for a simple canvas operation?

I'm having trouble with the code below. It's supposed to display a black box on the screen, but for some reason it's not working properly. The page is titled Chatroom so at least that part seems to be correct... <html> <head> &l ...

Clicking on the Ng button will display a datepicker in Onsen UI

Is there a method to display a DatePicker by clicking on a specific div element? <input type="date" ...> This will reveal a native datepicker. ...

Tips for preventing redundant HTTPInterceptor requests when transitioning between RxJS mergeMap operations

My system utilizes two JWT tokens: a Refresh Token (expires after 7 days) and an Access Token (expires after 15 minutes). These tokens are securely stored on httpOnly cookies and can be accessed via the server. The refresh method generates a new token and ...

executing gulp and express at the same time

Successfully set up Gulp, node, and express. Gulp is watching my tasks while express is running on port 3001. However, when I visit localhost:3000, I see my index.html with CSS, but navigating to localhost:3001 shows the same index.html without CSS. How ca ...

Issue with page scrolling while utilizing the Wow.js jQuery plugin

While using the Wow.js plugin for scroll animations, I encountered an issue on mobile phones. When reaching the Pricings section, scrolling becomes impossible for some reason. I am utilizing Bootstrap 3 in this project. Despite attempting to modify the an ...

How to transfer pairs of data from a cell array to a vector in MATLAB

Is there a way to extract the initial row of a cell array that consists of doubles and place it into a vector, all without utilizing a 'for' loop? ...

Ways to create different sections for ng-repeat data in AngularJS

I have a list of data elements that I am displaying using ng-repeat which currently prints as follows: data1 data2 data3 data4 data5 data6 However, I would like to display these data elements in sections, like this: data1 data3 data5 data2 data ...

Access to the Express Node.js server is restricted to the machine that is currently hosting the server

I am facing a beginner issue with using express. I am on Ubuntu 14.04 and created a new directory where I ran "express" in the terminal to set up a project template. Following that, I ran "npm install" to install the dependencies. I then made changes to &a ...

How to Retrieve Only a Single Value from an Array Using JavaScript

Here is an example array: data:[ {key: "1", value: "a"}, {key: "2", value: "b"}, {key: "3", value: "c"}] I need help transforming the array into this format: data:{"1","a","2","b","3","c"} ...

Is it feasible to send props to { children } within a React functional component?

Workaround presented below. I am attempting to send props down to a child component using {children}. The Parent component: const ParentComp = ({ children, propsToSendToChild }) => ( <div>Dynamic component content: {children} &l ...

Storing Image URLs as Object Properties in Firebase Storage: A Quick Guide

When uploading an image to Firebase Storage and retrieving its downloadURL, I have created a node called ADS in the Firebase database along with a newAd object within that node. My goal is to save the downloadURL of the image in newAd.picLink, which is ...

The console does not display client-side errors in node.js

When working on a school Chromebook with disabled developer tools, debugging client-side code in node.js can be challenging. Without access to error messages, it's frustrating to encounter issues that cause the code to stop working without any indicat ...

manipulating the HTML of another screen

I have a unique setup with two screens on different monitors, where one acts as a controller for the other that displays content to the audience. I want to use HTML to showcase the contents on both screens simultaneously. Right now, I'm facing a chall ...

VueJS: Preloading data prior to and following component initialization

VueJS is a new technology for me, and I'm currently working on a component that needs to retrieve data from an API before loading the corresponding route. The component should only load once the data is fetched. Additionally, after the component is cr ...

Pointers in C/C++ may compile successfully, only to encounter a segmentation fault error during runtime

Below is a code snippet from a larger program I am working on: double *pos_x_h[224]; double *pos_y_h[224]; const double A = 1; const int N = 224; double d_0; double alpha; void initialize(double nu, int rows = 16, int columns = 14) ...