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

The Express GET route does not support parameters or additional paths

I am facing an issue with making a fetch request when trying to add additional path or parameters... Here is what I want to achieve: const fetchOwnerCardList = () => { fetch("http://localhost:5000/api/card/ownerCards", { method: "GET", header ...

Navigating the complexities of extracting and storing a data type from a collection of objects

Dealing with a messy API that returns inconsistent values is quite challenging. Instead of manually creating types for each entry, I am looking for a way to infer the types programmatically. One approach could be by analyzing an array like this: const arr ...

Delay the fading in of an element using jQuery

Is there a way to remove the pause between the images in my JavaScript/jQuery slideshow when fading in and out? I attempted using a small delay, but it still didn't eliminate the blank space. Any suggestions? Check out the code on jsfiddle: https://j ...

Changing the variable within a promise in Angular 1

There seems to be an issue with updating a variable within the callback function of a promise, as shown in the code snippet below: $scope.showSelected= function (node){ var promise = $http.get("http://127.0.0.1:5000/getResource?ldpr="+nod ...

I am looking to create a counter in NextJS that will store its value in a database for persistent storage. How can

In my NextJS and ReactJS project, I am creating a like-counter feature that will keep track of the number of likes a user can give. The maximum limit for likes is set to 100. The count is stored in a FaunaDB. While I have successfully displayed the curren ...

Leveraging jQuery in Content Scripts for Chrome Extensions

I am currently working on developing a Chrome extension that will prompt a small input whenever a user highlights text on a webpage (similar to Medium's feature that allows you to tweet highlighted text). While I am making progress, I believe using j ...

The content in tinymce cannot be edited or removed

Is there a method to prevent certain content within the tinyMCE Editor from being edited or removed? While I know that adding a class "mceNonEditable" can make a div non-editable, it can still be deleted. Is there a way to make it unremovable as well? ...

Exploring File Reading and 2-Dimensional Array with Array Bound Caution

import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStreamReader; public class ReadFromFile { public static void main(String[] args) { String ...

Contrast and combine information from two JavaScript arrays of objects

I am struggling with comparing two arrays of objects based on a key. My goal is to compare the values, subtracting them when the keys match and displaying negative values for those not found in my target array. Additionally, I want to include all target o ...

The interface vanishes upon the integration of TinyMCE into the module

Currently, I am working on a project using Angular-fullstack and attempting to integrate ui-TinyMCE. However, I encountered an issue when I made the following changes: angular.module('academiaUnitateApp') .controller('NewEntryCtrl', ...

Positioning oversized images in a React Native application

Looking to showcase two images side by side using React Native, where I can customize the screen percentage each image takes up. The combined size of the images will exceed the horizontal screen space available, so I want them to maintain their original di ...

Activating and deactivating event capturing in Vue.js

Incorporating Vue.js into my project has been a game-changer. One interesting aspect is the event listener's third option, known as capture. For instance: element.addEventListener("click", function(){}, true); I'm curious if it's ...

Altering Image Order Across Various Slides

I have customized a parallax website template that is divided into various sections and slides. I want to incorporate a fixed image sequence on each slide that animates based on the scroll position. With 91 images in the animation sequence, it moves quickl ...

Incorporate 'Additional features' into the Navbar when adjusting window size

When the window is resized, I want to display a collapsed 'More options' button that will collapse all hidden <li> elements. Here is an example: <li id="menu_more_container" class="dropdown" style="display: none; ...

Steps for raising a unique error in an asynchronous callout

As I work on making async API callouts, there might be a need to throw custom errors based on the outcome. Also, part of this process involves deleting objects from S3. try { await s3.deleteObject(bucketParams); //Since S3 API does not provide ...

endless cycle of scrolling for div tags

My goal is to incorporate a tweet scroller on I believe it uses the tweet-scroller from Unfortunately, this link seems broken as the demo is not functioning. I searched for an alternative solution and came across http://jsfiddle.net/doktormolle/4c5tt/ ...

Ending a timed function in AngularJS 1

As part of my Angular JS 1 learning journey, I am working on a small test involving text areas that display text using Angular functions when a user enters and exits them. The enter function has a 3-second delay, while the exit function waits for 5 seconds ...

Is there a way to efficiently navigate a local JSON file using React JS?

What is the best way to extract data from a JSON file and utilize it within my code? I attempted importing the file and logging it in the console, but all I get is Object {}: import jsonData from "./file.json"; console.log(jsonData); This is the content ...

Learn how to design a customized loading screen using CSS with Phonegap

Currently working in Android with Phonegap / Cordova, I am faced with the challenge of optimizing page loading time due to numerous DOM objects being created. To address this issue, I am attempting to implement a "Loading..." screen to prevent users from b ...

Guide on setting up ShareThis on a Vue.js project

I attempted to include this code in the public index.html file: <script type='text/javascript' src='https://platform-api.sharethis.com/js/sharethis.js#property=5f4e15b2e56e550012ae1e77&product=inline-share-buttons' async='a ...