Eliminate items from one array when there is a corresponding match in a separate array using JavaScript

I am working with 2 JavaScript arrays

First Array

var columns=[{name: 'id', default: true}, {name: 'type', default: true},{name: 'typeName', default: true}, {name: 'client', default: false}];

Second Array

var unSelect=["id", "type", "typeName"]

Now I need to create a new array, Third Array, which contains only elements that do not match the name property in both previous arrays.

In this scenario:

var thirdArray=[{name: 'client', default: false}]

I attempted to use splice method but encountered issues with index matching.

Answer №1

One effective way to accomplish this task is by utilizing the Array.prototype.map function. By using this function, you can loop through an array and specify what should be returned during each iteration.

var updatedItems = originalArray.map(function(item) {

   if (filteredItems.indexOf(item.name) < 0)   // Check if item's name is not in the filtered items
     return item;                           // If true, return the current element 
})

Answer №2

Consider utilizing the filter method like this:

var unSelect=["id", "type", "typeName"];
var array3 = columns.filter(function(obj){
  return unSelect.indexOf( obj.name ) == -1;
});

DEMO

var columns = [{
  name: 'id',
  default: true
}, {
  name: 'type',
  default: true
}, {
  name: 'typeName',
  default: true
}, {
  name: 'client',
  default: false
}];
var unSelect = ["id", "type", "typeName"];
var array3 = columns.filter(function(obj) {
  return unSelect.indexOf(obj.name) == -1;
});
console.log(array3);

Answer №3

One way to improve the speed of accessing unwanted items is by using a hash table instead of the indexOf method.

var elements = [{ tag: 'div', active: true }, { tag: 'p', active: true }, { tag: 'a', active: false }, { tag: 'span', active: false }],
    exclude = ["a", "span"],
    hashtable = Object.create(null),
    output;

exclude.forEach(function (item) {
    hashtable[item] = true;
});

output = elements.filter(function (item) {
    return !hashtable[item.tag];
});

console.log(output);

Answer №4

My approach to this problem involves utilizing the combination of Array.prototype.filter() and Array.prototype.some().

const columns = [{name: 'id', default: true}, {name: 'type', default: true},{name: 'typeName', default: true}, {name: 'client', default: false}],
   unSelect = ["id", "type", "typeName"],
   filteredColumns = columns.filter(col => !unSelect.some(val => val === col.name));
console.log(filteredColumns);

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 there a more efficient method to execute this AJAX request?

$('#request_song').autocomplete({ serviceUrl: '<%= ajax_path("trackName") %>', minChars:1, width: 300, delimiter: /(,|;)\s*/, deferRequestBy: 0, //miliseconds params: { artists: 'Yes' }, onSelect: functi ...

What is the best way to implement rate limiting for asynchronous API calls within a specific timeframe?

I have a project that requires me to make over 500 calls simultaneously from my NodeJS server to a third-party server. The issue is that the third-party server has a restriction of only allowing a maximum of 50 calls per second. Can someone assist me in im ...

The image is loaded correctly through the image picker, however, it is not displaying on the screen

When I click the button to pick an image from the gallery in this code, it is supposed to load the phone's gallery and display the selected image in the image component. Even though the image gets loaded properly (confirmed through test logs), it does ...

Issue with Dropzone not functioning correctly within Vue transition modal

I've implemented a dropzone function in the mounted function, which works perfectly when the dropzone is outside of a modal in the view. However, when I try to use it within a modal with a transition effect, it doesn't work. Any suggestions on ho ...

Are your file uploaders malfunctioning by saving empty image files?

I am currently working on a file uploader using JavaScript and Classic ASP. The process involves importing an image into a canvas, converting it to a base64 URL, and then sending that URL to the ASP script for decoding and downloading. Although my AJAX re ...

Issue: The error message "articales.forEach is not a function" is indicating

app.get('/', (req, res) => { const articales = { title: 'Test Articles', createdAt: Date.now(), description: "Test Description" } res.render('index', { articales : articales }) }) <div ...

Javascript issue: opening mail client causes page to lose focus

Looking for a solution! I'm dealing with an iPad app that runs html5 pages... one specific page requires an email to be sent which triggers the Mail program using this code var mailLink = 'mailto:' + recipientEmail +'?subject=PDFs ...

What's the best way to showcase array values in JavaScript?

I am facing an issue where I am trying to display all values from the array "categories", but I keep getting [object object] or undefined. The problem seems to be occurring in the code within the last lines of the if statement, specifically when I try to ...

The error message "Required parameter not provided" appeared when trying to utilize a nested dynamic route in Next.js

Issue: The error message indicates that the required parameter (plantName) was not provided as a string in getStaticPaths for /plants/[plantName]/streaming-data/[panel] The error above is being displayed. My folder structure follows this pattern: plants > ...

Is it possible to change the text of a scrollspy dropdown to a default text when it is not actively tracking any items?

I am new to Vue and currently implementing Bootstrap Vue Scrollspy (view example here). My sticky dropdown is tracking all referenced content and updates with the current section in view. You can check out my code sample here. Is there a way to set the d ...

"Using the power of jQuery to efficiently bind events to elements through associative

I am attempting to link the same action to 3 checkboxes, with a different outcome for each: var checkboxes = { 'option1' : 'result1', 'option2' : 'result2', 'option3' : 'result3', }; ...

Having difficulty executing the Cypress open command within a Next.js project that uses Typescript

I'm having trouble running cypress open in my Next.js project with Typescript. When I run the command, I encounter the following issues: % npm run cypress:open > [email protected] cypress:open > cypress open DevTools listening on ws: ...

How to add a jQuery function to a Rails 3 if statement?

I followed a Rails 3 tutorial on creating a multi-step form which you can check out here. Additionally, I incorporated Stripe payment functionality in my app using another railscast found here. Within my application, the payment form is hidden using jQuer ...

Is it a usual technique to retrieve dynamic content using PhoneGap?

Recently, I've been utilizing phonegap for creating mobile applications on various platforms. I've noticed the need to use AJAX calls within JavaScript to fetch dynamic content. I'm curious, is it a standard practice in HTML5 apps to retrie ...

What are the steps to resolve a Fetch request issue with a Node.js server?

I am attempting to make a simple POST request using the fetch method. I am working on building a contact form using Vanilla Javascript, HTML, and CSS on the front end, while utilizing Node.js / Express on the backend. Take a look at my front end code: ...

What can you do with jQuery and an array or JSON data

Imagine having the following array: [{k:2, v:"Stack"}, {k:5, v:"Over"}, , {k:9, v:"flow"}] Is there a way to select elements based on certain criteria without using a traditional for/foreach loop? For example, can I select all keys with values less than ...

Transforming a numpy array of dimensions (M, N, O) into a point cloud

In my project, I am working with a large 3D numpy array measuring 2000 x 2000 x 300. This array consists of 300 binary images where pixel values are either 0 or 1. My goal is to obtain a new numpy array with dimensions P x 3, where P represents the number ...

Using AngularJS to compare values against user input to determine if they are greater or lesser

When a user inputs data into an input field, it must fall within the range of values retrieved from the database. The value entered by the user should meet either the minimum, maximum, or default value obtained from the database. For instance, if the minim ...

Ways to emphasize search outcomes in Flask/HTML?

I am currently working on creating a search box using HTML and the Flask framework in Python. Below is the layout I am working with: Layout My goal is to input text into the search box and have it highlighted within the text area on the same HTML page. F ...

Refresh Form (Reactive Forms)

This is the HTML code snippet: <div class="container"> <ng-template [ngIf]="userIsAuthenticated"> <form [formGroup]='form' name="test"> <div class="form-group"> <input type="text" class="form-contr ...