I would like to find the difference between two arrays by creating a third array that only contains the elements not found in the first array

Subtracting elements from two arrays. arr1=["AT","IN","UK","US"] and arr2=["UK","ZA"]. I want the result to be arr1-arr2 = ["AT","IN","US"]

I have attempted to perform the subtraction of the arrays as described above, but instead of obtaining the correct output, I keep getting arr1[]. Here is the code I used:

var firstArray = ["AT","IN","UK","US"]; 
var secondArray= ["UK","ZA"] ;
var subtractedArray = [];
subtractedArray = firstArray ;

console.log(subtractedArray);
for(i=0;i<firstArray.length;i++)
{
    for(j=0;j<=secondArray.length;j++)
    {
    if (firstArray.includes(secondArray[j]))   
        {
            var index = subtractedArray.indexOf(secondArray[j]);
            if (index > -1) {
                subtractedArray.splice(index, 1);
            }
        }
    }
}

Answer №1

To eliminate the element in array a that is also present in array b, you can use the filter() method.

Iterate through array a using the filter() method. During each iteration, check if the element in array a is not found in array b. The filter() method will retain the element if the callback function returns true; otherwise, it will remove the current element in the iteration.

const a = ['AT','IN','UK','US'];
const b = ['UK','ZA'];
const r = a.filter(i => b.indexOf(i) === -1)
console.log(r)

Answer №2

Here's a simple solution:

prevCountries.filter(x => !sectedCountries.includes(x))

Alternatively, for a potentially faster solution utilizing sets for efficient membership test:

let sectedSet = new Set(sectedCountries)
prevCountries.filter(x => !sectedSet.has(x))

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

Using a for loop to cycle through an array and generate sibling div elements

I'm attempting to display the content of the gameTwo array in two child divs under the game2 element. However, the issue I'm facing is that the loop creates a child of a child on the second iteration. Could someone provide guidance on how I can a ...

Load External HTML content into webpage along with executing JavaScript code and triggering JS functions upon loading

I'm in search of a super lightweight solution that can effectively load an external HTML file into a page using only vanilla JavaScript. The external file contains HTML, CSS, and JS. Essentially, I want to create a concise JS snippet that loads a butt ...

The implementation of local JSON instead of external JSONP in Angular

I am exploring the option of storing a json-file on the same server as my Angular app. I am wondering about how I can modify this code to read from a locally stored json file: ergastAPI.getDrivers = function() { return $http({ method: 'GET&apos ...

Alter the configuration of a JSON object

I'm currently working on modifying the following JSON text. It has the structure as shown below: { "cabecera": { "tipo_cambio": "", "fecha_emision": "", "total": "" }, "detalle": { "940b130369614bd6b687dc5b41623439": { " ...

Using the drag and drop feature with the v-textarea component in Vuetify

Struggling to incorporate a Drag and Drop feature on vuetify v-textarea. Encountering an issue where clicking on the v-textarea results in the value from a dropped component being removed. Unsure if it's a flaw in my code or a limitation in vuetify v- ...

"Make your slides smooth and responsive with the unslick option in slick

Currently implementing the Slick Slider on a WordPress website. The slider is designed to display 3 columns at a screen size of 1024px and above. When the screen size drops below 1024px, the slider adjusts to show 2 columns, and on mobile devices, it swit ...

divide an array into two separate arrays depending on whether the index position is odd or even

Here is an example array: Arr1 = [1,1,2,2,3,8,4,6]. I'm trying to divide this array into two new arrays based on the odd or even position of elements. Can anyone provide a solution? New Array 1 (odd positions): [1,2,3,4] New Array 2 (even positions) ...

Developing a Node.js and Express REST API for generating tailored routes for custom fields

I'm currently using node.js and express framework to build my REST API server. One of the features I want to implement is similar to the Facebook graph API, where I can pass specific fields in my API routes like: /me?fields=address,birthday,email,do ...

While it includes a new section, it fails to refresh the navbar

Upon clicking the button to add a new section, the section gets added successfully. However, the navbar does not get updated as expected. It should dynamically update the navbar to display both the existing sections and the new section added using JavaScri ...

Encountering difficulty invoking a component method from d3's call() function

My current setup involves using D3 to drag and drop links in the following manner: .call(d3.drag() .on("start", linkDragStart) .on("drag", linkDragging) .on("end", linkDragEnd)); Recently, I decided to extract this functionality into a separate met ...

ReactJS: Trouble encountered while parsing information from JSON data

Currently, I am facing an issue while trying to pass data from my JSON file to my ReactJS application. The error message that I am encountering is as follows: TypeError: Cannot read property 'mainPage' of undefined Upon console.logging siteDa ...

What is the best way to sequence the functions in an AJAX workflow?

I'm currently working on optimizing the execution order of my functions. There are 3 key functions in my workflow: function 1 - populates and selects options in a dropdown using JSON function 2 - does the same for a second dropdown function 3 - ...

Step by step guide to verifying email addresses with Selenium WebDriver

A feature in my EXTJS application includes a page with an Email button. When this button is clicked, it generates a link to the page contents and opens the default email client with this link in the body. Upon inspecting the DOM, I found that the Email bu ...

Navigating Angular with relative paths: A guide to locating resources

Here is the structure of my app: index.html main.ts app |--main.component.html |--main.component.ts |--app.module.ts |--note.png ... etc I am trying to include the note.png file in main.component.html which is located in the same folder. I have att ...

Challenges with dividing input into array indices in C programming

Currently, I am diving into the world of C programming and facing an issue with splitting a string of text. My goal is to prompt the user to input multiple words separated by spaces in a single line, and then have the program split these words and store ...

Closing md-tooltip automatically after a specified timeout period

I've set up md-chips in Angular material with the following configuration: <md-chips md-chips-disable-input ng-model="session.participants"> <!-- Chip removal button template --> <button md-chip-remove class ...

Steps for retrieving user timezone offset and transmitting it to the server in an ASP.net application

I need assistance with capturing and sending a user's timezone or offset when they successfully sign in. I came across the "getTimezoneOffset" method in JavaScript, but I'm unsure how to automatically send this data without the user explicitly in ...

What's causing the failure in the execution of the "Verify version" step?

Upon reviewing the 3DSecure GlobalPay documentation, my team decided to integrate it using JSON, incorporating our own client-side implementation. This decision was made because we already have another integration with a different 3DS verification service ...

The MUI persistent drawer navigation bar becomes dysfunctional when accessing a specific route

Exploring the MUI library for the first time, I successfully created a navigation bar that functions properly for one route (Dashboard). However, when attempting to implement it on the candidate route, it collapses as shown in this Screengrab of collapsed ...

Choosing a Value from a WP_Post Object in PHP

I stumbled upon this sample array/object structure: //$monday array values Array ( [menu_item1] => [menu_item2] => Array ( [0] => WP_Post Object ( [ID] => 530 [post_content] => Food selection 2 [post_title] => Food 2 ) ) Being a novi ...