Deleting elements from arrayA that do not exist in arrayB using JavaScript

Seeking guidance on a small project of mine.

For example, I have these two arrays:

chosenItems = ['apple', 'banana', 'cherry', 'date', 'kiwi']
availableFruits = ['apple', 'cherry', 'grape', 'kiwi']

My goal is to compare the chosenItems array with the availableFruits array. If an item in chosenItems is not present in availableFruits, then it should be removed from chosenItems.

Outcome:

chosenItems = ['apple' 'cherry', 'kiwi']
availableFruits = ['apple', 'cherry', 'grape', 'kiwi']

I am aware that I can achieve this task using for-loops, but I am interested in exploring if there is a more efficient way to accomplish this using JavaScript.

Answer №1

If you want to achieve this, you can also leverage ES6's filter method.

selectedItems = ['a', 'b', 'c', 'd', 'z']
availableItems = ['a', 'c', 'z']

const result = selectedItems.filter(item => availableItems.includes(item));

console.log(result)

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

Adding an Icon to a Tab in Ant Design - A Step-by-Step Guide

Is there a way to include an icon before the title of each open tab? I am currently using the antd library for tab creation, which doesn't provide a direct option for adding icons. Here is my code snippet along with a link to the jsfiddle https://jsfi ...

Discovering the right row to input the data and successfully integrating it: What is the best

Below is the code I am using to add a new task: <fieldset> <legend>Create New Task</legend> <input type="text" ng-model="subtaskname" placeholder="Subtask Name" ><br /> <select id="s1" ng-model="selectedItem" ng-options=" ...

What is the best way to display the information stored in a nested JSON hash table onto a PowerShell output?

Is there a way to output all the contents of a nested JSON hash table in PowerShell in a single line? $json = @" { "outer": "value1", "outerArray": [ "value2", "value3" ], "outerHash": { "inner": "value4", " ...

"Accessing your account only requires a simple two-click login process

Why do I need to click the log in button twice for data validation on my forum website? While designing a forum website, I noticed that users have to click the log-in button twice before the system validates and processes the input data. Below is the code ...

Is utilizing v-model to update the Vuex store a recommended practice?

Hello there! As a newcomer to Vue, I find myself facing a dilemma that has been weighing on my mind. I'm confused about whether we should utilize the v-model directive to make changes to the Vuex store. While Vuex guidelines suggest modifying the stor ...

Differences in accessing the previous state between React's useCallback and useState's setState(prevState)

It has come to my attention that useCallback functions recreate themselves when their dependencies change, acting as a sort of wrapper for memoizing functions. This can be particularly useful for ensuring access to the most up-to-date state in useEffect ca ...

Tips for preloading an image with Vue's built-in tool

My Vue CLI app contains a feature where a series of images transition when a user clicks a button. The issue arises when the image loading is delayed until the button click, causing a choppy experience as the images suddenly pop in during the transition, d ...

Managing User Feedback with Ajax, JQuery, and PHP

Imagine you're using ajax to send data. The server processes it (in PHP) and sends back a response that can be captured with complete: function(data) { //WRITE HTML TO DIV $('#somehing').html(data) } The big question is: how can you modify ...

Tips for adjusting the dimensions of my chart using JavaScript or Jquery

Utilizing DevExtreme widgets for the creation of a line chart in jQuery as shown below: var dataSource = [{"Date Range": "August-2018", Benelux: 194, Czech_Slovakia: 128, ...

What is the best method to trigger a form submission using Jquery?

Happy New Year! Wishing you a joyful 2015! I have a basic PHP contact form that I'm validating with Parsley.js. The validation is working well, but I'm receiving a high volume of spam emails. I think that if I make the form submission dependent ...

Having trouble capturing the CHANNEL_ANSWER event in my node.js script when communicating with Freeswitch

Greetings to all! I have a query regarding freeswitch. Although my experience with freeswitch is limited, I am currently working on connecting my node js script to the freeswitch server. So far, I have managed to establish a successful connection and gene ...

What is the best approach for addressing null values within my sorting function?

I created a React table with sortable headers for ascending and descending values. It works by converting string values to numbers for sorting. However, my numeric(x) function encounters an issue when it comes across a null value in my dataset. This is th ...

Compatibility issues between jQuery and AngularJS are causing problems

Currently, I am facing a compatibility issue between RequireJS and Angular in my setup. Everything functions without any problems when using jQuery version 1.7.2. However, I wanted to upgrade to jQuery 1.8.1 along with jQuery UI, but unfortunately, my Angu ...

How can I address the issue of an inner content scroll bar?

I am facing an issue with the scroll bar on inner content. When I hover over an arrow on the inner content, the scroll bar appears as desired. However, it changes the content in a way that looks odd. Is there a solution to have a scroll bar on the inner co ...

Using Paper Checkbox to Toggle the Visibility of a Div in Polymer

Having experience with Meteor, I typically used JQuery to toggle the display of a div along with paper-checkbox: HTML: <paper-checkbox name="remoteLocation" id="remote-chk" checked>Remote Location</paper-checkbox> <div id="autoUpdate" clas ...

Ensure to verify the input's value by clicking the button

Upon clicking a button, I am trying to determine if there is any content in an input field. However, it seems that the check only happens once when the website first loads. Subsequent clicks of the button do not detect any new input values entered into the ...

When resizing the window, the width change in JQuery always resets to 0

I've been trying to adjust the width of a div element when the window is resized, but for some reason, the width always ends up being 0 after the resize event. function resizeUploadField() { var uploadInputField = $('.input-append&apo ...

Encountering a POST 405 error message stating "Method not allowed" while attempting to send an AJAX request in Laravel

I've been attempting to create a simple AJAX request to populate a menu in Laravel, but I've been running into some difficulties getting it to function correctly. Despite spending several hours searching for a solution, I'm still unsure of ...

Tips for displaying two dynamic variables that are interdependent

For instance: Controller: AllBooks[{ book1:{ hardcover{price:25.99},e-book{price:1.99} } }, book2:{ hardcover{price:60.00},e-book{price:2.99} }]; $scope.bookchoice = function(selectedBook) { $rootScope.choice = selectedBook;} $scope.booktype = functio ...

Deploying a React App to Github Pages Results in a Blank Screen

After successfully uploading a simple react app onto GitHub pages using gh-pages, I attempted to import the Shards dashboard project (https://github.com/DesignRevision/shards-dashboard-react) onto my GitHub page. Unfortunately, all I see is a blank page. ...