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

There was a lack of information received from the callback function when utilizing jQuery AJAX with JSON in PHP

I've been experimenting with the code found here: https://gist.github.com/Exeu/4674423. This particular code is designed to connect to Amazon's wsdl and fetch product information. Unfortunately, I've encountered some difficulties in getting ...

What is the best way to check if the user's input corresponds to any of the values stored in an array in Java?

As a Java beginner, I have been tasked with creating a word guessing console game that utilizes conditions, loops, and arrays. The game should determine if the player's input matches any words in the array. import java.util.Scanner; public class ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

Tabulator and its convenient scrollable column feature allows for easy navigation

In case my tabulator column is exceeding its length, is there a way to enable scroll functionality for that specific column? Although the resizable rows feature permits users to resize and view all the content, can a scrollbar be implemented exclusively ...

I'm in need of some assistance - could somebody kindly point out where I may be making

I'm encountering an issue where I'm only receiving two rows of data from the database instead of four. I've reviewed my code but can't seem to pinpoint any problems. Can anyone assist me with this? Here is the code snippet: $sql = mys ...

How to send props from a Vue.js component tag in an HTML file

I'm facing an issue with passing props from the HTML to the JavaScript code and then down to a Vue component. Here's a snippet of my index.html file: <div id="js-group-discounts"> <div class="form-group required"> <datepick ...

Using Node.js, we can create a program that makes repetitive calls to the same API in a

My task involves making recursive API calls using request promise. After receiving the results from the API, I need to write them into an excel file. Below is a sample response from the API: { "totalRecords": 9524, "size": 20, "currentPage": 1, "totalPage ...

What is the best method for extracting a JSON datetime string in Python?

When making a call from Python to a remote API, the returned data is in JSON format. To parse this data, I use the json module with json.loads(). The issue I am facing pertains to dates - the system I am calling returns the date formatted as follows: /Dat ...

Is Javascript Profiling a feature available in Firebug Lite?

Exploring the world of JavaScript profiles, I decided to step away from the usual Chrome Developer tools. Can Firebug Lite for Google Chrome provide Javascript Profiling functionality? ...

What is the best way to continuously click a JavaScript link until it disappears?

Many websites utilize single-page pagination to display more content with each click. It can be beneficial to view all the content on one page, such as for web crawling purposes. Much like automatically clicking a button using Greasemonkey, how can JavaScr ...

Jenkins is experiencing issues with starting up or reconnecting - It is hanging and displaying a severe error message: unable to properly read the JSON file provided at [/var/lib/jenkins/cb-envelope/envelope.json]

Jenkins: Version 2.89.4-x rolling Encountered slow performance issues with Jenkins due to memory problems. After trying to restart Jenkins using the sudo or usual method, a severe issue was encountered. Eventually, restarted the entire Jenkins machine in ...

I recently discovered how to modify the video source (src) within an html5 source tag, but I am encountering varied outcomes when using it within a function or with inline javascript

When attempting to change the src of a video tag using Javascript, I encountered an issue. The code works fine when placed inline, but as soon as I try to include it within a function or in the "onclick" event of a button tag, nothing happens. There are no ...

I'm having an issue with my Bootstrap tabs - they seem to be unresponsive when clicked

I've been working on a Bootstrap website and have run into some issues that I can't seem to resolve. One problem I encountered was with a set of tabs that were supposed to be interactive, but for some reason, they weren't working as expected ...

Choosing a specific element within another element of the same type using JQuery

I've created a complex nested HTML structure shown below: <ul class="root"> <li>Foo 1 <label class="bar-class">bar</label> <ul> <li>Foo 2 <label class="bar-class">bar</label> ...

The alert box fails to display in the correct orientation when the condition is activated

Currently, I am working on implementing a sign-up feature using PHP. My main goal is to successfully store the user-entered data in MySQL database while ensuring that no duplicate usernames are allowed during account creation. Although everything is functi ...

Having issues with json_decode not functioning correctly after using JSON stringify

After encoding a JavaScript array into JSON and posting it to PHP, I encountered an issue. Before posting the data, when I checked a value in the array using console.log(selection[878][2824]), I received the expected result. However, after encoding the var ...

Organize your blog content by utilizing post IDs as the designated id attribute

What is the best way to format blog posts and comments in HTML so that I can easily manipulate them later using jQuery/Javascript for tasks like updating, deleting, or making Ajax calls? I am considering using the IDs (primary keys in the database) of the ...

Web page experiencing "increased magnification during loading"

I've been experiencing an issue with my mobile site where the page loads as if it's zoomed in every time. I can easily scale it on a touch phone to make it look right, but I'm looking for ideas on how to prevent this from happening altogethe ...

Encountering an issue when attempting to host a Next.js application on Vercel

Why is it important to regularly do this task as per the instructions provided in the link? Info - Working on creating a highly efficient production build... Note: Next.js now collects completely anonymous telemetry data on user usage. This data helps sha ...

Saving a MongoDB document within an array in Node.js and retrieving it

I am working on retrieving specific documents from MongoDB using Node.js and storing them in an array. const getStockComments = async (req) => { const stockname = req.params.stockName; var comments = []; var data = []; const stock = await sto ...