Are there any lodash functions available for removing an array that matches another array from the main array?

I currently have two arrays named available and selected, each containing certain values. I also have another array called finalAvailable where I want to include all items from the available array except those that are already present in the selected array. This is illustrated in the example below:

var available = ["A", "B", "C", "D", "E"];
var selected = ["B", "C"];

Therefore, the contents of the finalAvailable array should be as follows:

var finalAvailable = ["A", "D", "E"];

I have successfully implemented a code to achieve this functionality. However, my team lead advised me to explore potential options within Lodash to accomplish the same task. Unfortunately, after conducting some research, I couldn't find any specific function in Lodash that directly addresses this requirement. I'm unsure if I may have overlooked something.

If anyone is aware of a similar feature available in Lodash, kindly share that information with me.

The current code I am using for this operation is provided below:

var available = ["A", "B", "C", "D", "E"];
var selected = ["B", "C"];

var finalAvailable = [];

for (var i = 0; i < available.length; i++) {
    var flag = true;
    for (var j = 0; j < selected.length; j++) {
        if (available[i] == selected[j]) {
            flag = false;
        }
    }
    if (flag) {
        finalAvailable.push(available[i])
    }
}

Answer №1

Give this a try

var options = ["X", "Y", "Z"];
var choices = ["Y", "Z"];

var remainingOptions = _.filter(options, function (item) {
  return _.indexOf(choices, item) === -1    
});

console.log(remainingOptions);

// alternatively, you can use _.difference
console.log(_.difference(options, choices));
<script src="https://rawgit.com/lodash/lodash/3.0.1/lodash.min.js"></script>
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

Answer №2

Attempt this code snippet without using Lodash library:

const availableItems = ["A", "B", "C", "D", "E"];
const selectedItems = ["B", "C"];

const remainingAvailableItems = availableItems.filter(item => !selectedItems.includes(item));
console.log(remainingAvailableItems);

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

Transforming a collection of items into a JSON format string

UPDATE: There was a mistake in the programming, please refrain from submitting answers. This question will be removed. If you have already submitted an answer, kindly delete it. I am attempting to submit a form using jQuery and ajax. One of the fields con ...

Adding client-side scripts to a web page in a Node.js environment

Currently, I am embarking on a project involving ts, node, and express. My primary query is whether there exists a method to incorporate typescript files into HTML/ejs that can be executed on the client side (allowing access to document e.t.c., similar to ...

Error: req.body or req.params.id is not defined in the current context (PUT and PATCH requests)

I'm experiencing an issue where both req.body and req.params.id are returning undefined even though I am using express.json() before the app.patch. I have tried changing the route to /:id, but that did not resolve the problem. Interestingly, it works ...

HTML - Using Tables to Add and Edit Rows

Take a look at this demo on JSFiddle for my project: Demo jsfiddle I'm currently in the process of creating a table with various functionalities. The function "sortTable" is responsible for sorting the table and it's functioning as expected. T ...

What is the best way to utilize MUI breakpoints for displaying images based on different screen sizes?

I need help displaying an image based on the screen size using MUI breakpoints. I'm struggling to understand how to implement this with MUI. Can someone assist me with the breakpoints? interface EmptyStateProps { title: string; description: string ...

Calculate the time difference in hours using time zone in Javascript

Within my JavaScript object, I have the following information: var dateobj = { date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3 } var date = new Date(); var options = { timeZone: dateobj.timezone }; var curr_date ...

Creating synchronization mechanisms for events in JavaScript/TypeScript through the use of async/await and Promises

I have a complex, lengthy asynchronous process written in TypeScript/JavaScript that spans multiple libraries and functions. Once the data processing is complete, it triggers a function processComplete() to indicate its finish: processComplete(); // Signa ...

The dimensions of GridStack items specified in pixels for both height and width

I am facing a challenge with my GridStack items, which each contain elements like graphs that need to be re-rendered when the size of the gridstack item (cell) changes. I am attempting to use the change event on GridStack to detect the modified items and t ...

Having trouble getting the video to load on your Mozilla Firefox browser?

Unable to play video on Firefox. Error message: URL.createObjectURL(video): Error decoding media resource blob: NS_ERROR_DOM_MEDIA_FATAL_ERR (0x806e0005) Details: Decoder may not support the requested video format with YUV444 chroma subsampling. Tried usi ...

Class does not have the capability to deserialize an array

I encountered this issue with my code (see image): Here is the snippet of my code: function CheckLoginData() { var user = []; user.Email = $("#tbEmail").val(); user.Password = $("#tbPassword").val(); $.ajax({ type: "POST", contentType: "applic ...

Extract data from a JSON file and refine an array

Currently, I am working with reactjs and have an array stored in a json file. My current task involves filtering this array using the selectYear function. However, when attempting to filter the data using date.filter, I encounter the following error: An ...

Strategies for avoiding a hover component from causing distortion to its parent component in React

I am encountering an issue with a hover component that is causing distortion in its parent component when displayed. Essentially, I need to prevent the hover component from affecting the layout of its container. Below is the code snippet: Styling for Lang ...

Looking to bring in a non-ES6 library into VueJS without using export statements

Currently, I am faced with an interesting challenge. For a forthcoming VueJS project, we must utilize a library that is quite outdated but there is simply not enough time to redevelop it. The library is essentially a JavaScript file which consists of num ...

Tips to Avoid Multiple Executions of Javascript Code due to Caching

When I make a request to my Asp.net-MVC application, it returns a partial-view. public ActionResult AccountDetails() { return PartialView("~/Views/partials/Account/Details.cshtml"); } To load the partial view in my form, I use the following ...

How can I capture the 'ended' event from an HTML5 video tag using Ember in a controller?

I am having an issue with an hbs file that contains an html5 video tag: <video id="externalVideo" controls loop> <source src="../assets/videos/test.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video> I am ...

Could json.loads() be exploited for executing arbitrary code?

Does the json.loads function from Python's built-in json module pose any risk of allowing arbitrary code execution or other security vulnerabilities? I need to process JSON data from sources that may not be trustworthy. ...

The function to navigate, 'navTo', is not defined and so it cannot be read

I am trying to create a navigation button in my SAPUI5 application deployed on Fiori _onPageNavButtonPress: function () { var oHistory = History.getInstance(); var sPreviousHash = oHistory.getPreviousHash(); if (sPreviousHash !== ...

The functionality of Material Autocomplete is not compatible with InputProps

I am experiencing an issue with customizing the border of my TextField within my Autocomplete component. When I include the InputProps prop, the Autocomplete stops rendering Chips <Autocomplete multiple freeSolo options={options} render ...

Steps for retrieving the currently selected text inside a scrolled DIV

An imperfect DIV with text that requires a scroll bar For example: <div id="text" style='overflow:scroll;width:200px;height:200px'> <div style='font-size:64px;'>BIG TEXT</div> Lorem Ipsum is simply dummy text of th ...

Upgrading email functionality: Combining PHP mail() with AJAX

My issue revolves around using the mail() function. When AJAX code is present, the email gets sent but without any message (the subject is intact though). However, when I remove the AJAX code, the email goes through without any problems. I'm not well ...