Iterate through an array to extract specific objects and exclude them from another array

Within my code, I have an array named allItems that stores objects.

allItems = [
    { id: 1, name: 'item1' },
    { id: 2, name: 'item2' },
    { id: 3, name: 'item3' }
]

I am seeking a way to filter out the objects from this array that are also present in another array within my component.

fewItems = [
    { id: 2, name: 'item2' }
]

This means that the resulting array filteredItems should look like this:

filteredItems = [
    { id: 1, name: 'item1' },
    { id: 3, name: 'item3' }
]

If any additional object from allItems is subsequently added to fewItems, it should automatically disappear from the filteredItems array.

I aim to achieve this using vanilla JavaScript, without relying on any specific library.

Thank you in advance for your help!

Answer №1

selectedItems =  this.allItems.filter(a => {
    return !this.selectedFew.some(b => JSON.stringify(b) === JSON.stringify(a))
});

Answer №2

var allItems = [
     { id: 1, name: 'item1' },
        { id: 2, name: 'item2' },
        { id: 3, name: 'item3' }
    ];
    
    var fewItems = [
        { id: 2, name: 'item2' }
    ];
    
    var keys = Object.keys( fewItems[0] ) 
    
    var result = allItems.filter( 
      function(item){ 
        for( var k = fewItems.length-1; k>=0; --k){ 
          var dontWant = fewItems[k]; 
          var i=keys.length-1; 
          for( ; i>=0; --i ){ 
            if( dontWant[keys[i]] != item[keys[i]]){  break; } 
          } 
          if( i == -1){ return false;} 
        } 
        return true; 
      }
    );

    console.log(result)

Answer №3

JavaScript only solution

var allProducts = [
  { id: 1, name: 'product1' },
  { id: 2, name: 'product2' },
  { id: 3, name: 'product3' }
];

var fewProducts = [
  { id: 2, name: 'product2' }
];

var finalProducts = allProducts
  .filter(product => {
    for(let restrictedProduct of fewProducts) {
      if (JSON.stringify(restrictedProduct) === JSON.stringify(product)) {
        return false;
      }
    }
    return true;
  })

console.log(finalProducts);

Answer №4

var allItems = [
    { id: 1, name: 'item1' },
    { id: 2, name: 'item2' },
    { id: 3, name: 'item3' }
];

var fewItems = [
    { id: 2, name: 'item2' }
];

var result3 = _(allItems) 
        .differenceBy(fewItems, 'id', 'name')
        .map(_.partial(_.pick, _, 'id', 'name'))
        .value();

console.log(result3);

 
<script src='https://cdn.jsdelivr.net/lodash/4.17.2/lodash.min.js'></script>

EDIT

Without Lodash

var allItems = [
    { id: 1, name: 'item1' },
    { id: 2, name: 'item2' },
    { id: 3, name: 'item3' }
];

var fewItems = [
    { id: 2, name: 'item2' }
];


var props = ['id', 'name'];
var result = allItems.filter(function(o1){
     return !fewItems.some(function(o2){
        return o1.id === o2.id;        
    });
}).map(function(o){
     return props.reduce(function(newo, name){
        newo[name] = o[name];
        return newo;
    }, {});
});

console.log(result);

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

What is the method for selecting an element using CSS code in Protractor?

Having trouble clicking on the element with CSS Selector: <button _ngcontent-c16="" class="btn btn-flat btn-no-text btn-kebab-view"> <i _ngcontent-c16="" class="zmdi zmdi-more-vert"></i> </button> This is what I've t ...

Guide on incorporating one element into another with jquery

I am facing a challenge with the following code snippet: <p>Nuno</p> <p>Eimes</p> My goal is to transform it into this format: <p><a href="name/Nuno">Nuno</a></p> <p><a href="name/Eimes">Eimes& ...

Create a request for an update by utilizing Axios within a React and Material UI environment

I am completely new to React, and my experience with CRUD functionality is limited to ASP.NET MVC. I'm feeling a bit lost as none of the tutorials I've come across seem to cater to my specific situation. The tips I received previously were helpfu ...

Is there a way to retrieve all documents based on the start and end of a specific day?

One common issue I am facing involves submitting a date to my nodejs server in a specific format

 2018-11-02T00:36:00+05:30 // The actual time should be 12:36AM However, when examining the document in my database (using studio 3T), the format appear ...

What exactly do bootstrap, javascript, jquery, and ajax entail?

Exploring the world of client-side scripting to enhance web page dynamism and data collection has piqued my interest. I have come across programming languages like JavaScript, Ajax, and jQuery. However, uncertainty clouds my understanding as concepts remai ...

Add a text to the values in a column of a table when the IDs are the same

I am working on a project that involves updating a table based on a data change. The table has a column for ID and when the ID matches a specific variable, I need to append the word 'Updated!' next to it in the table cell. However, the code I hav ...

Creating responsive tabs that transition into a drop-down menu for mobile devices is a useful feature for

I am looking to create a responsive tab design that drops down like the example shown below: Desktop/Large Screen View https://i.stack.imgur.com/hiCYz.png Mobile View https://i.stack.imgur.com/gRxLv.png I have written some code for this, but I am unsure ...

Troubleshooting: Issues with Adding a New Row in Datatables using JQuery

CSS : <div class="datatable-header"> <button type="button" name="add" id="add" class="float-right btn btn-info">Add</button> </div> <div class="table-responsive"> <table ...

Error encountered when attempting to have multiple chrome.runtime.onMessage listeners - port disconnection issue

I am currently developing a chrome-extension that utilizes the Dexie indexedDB Wrapper, various jQuery Libraries, and syncfusion's eGrid to manage and display data. While I know this issue has been addressed multiple times in the past, I have encounte ...

React is unable to assign a class field beyond the scope of axios

class App extends React.Component { app: Application; ... componentDidMound() { axios.get(…).then(res => { this.app.currentUser = res.data.data; // setting value inside lambda function. console.log(this.app.currentUser); // ...

How to eliminate a hyperlink from an HTML element with the help of JQuery

Recently, I was assigned to revamp a website for the company I work for. However, upon closer inspection, I realized that the website is quite messy and relies heavily on templates, resulting in certain elements being auto-generated as active links. The i ...

Issue with Vue-Validator form validation not functioning properly on JS Fiddle

I'm having trouble with vue-validator on JSFiddle. Can someone please assist in troubleshooting the issue so I can proceed with my main question? Check out JSFiddle Html: <div id="app"> <validator name="instanceForm"> & ...

sending a parameter in the reverse url using JavaScript

coding in javascript let address = '{% url candidate_resume "cnd_id" %}'; address = address.replace("cnd_id",id); document.getElementById('cell2').innerHTML= '<a href="' + address + '"> View Resume < ...

Bootstrap4 does not support the <button> element

How can I achieve a 'collapse icon' floated to the left followed by Copyright © using Bootstrap 4? I've looked at similar questions on this topic, but none seem to provide a direct answer. Other questions contain different code with ob ...

Looking to create an Ajax Control Toolkit AutoCompleteExtender with results that are "similar"?

The Ajax AutoCompleteExtender is all set up and functioning properly, linked to a webservice that fetches results from SQL. Now, I want to enhance the user experience by providing similar results in case they can't recall the exact name of what they& ...

Unspecified tag name attribute in Vue that can be accessed in the browser

At the moment, I have encountered an issue with a selector in Vue returning undefined for {{ lens.price }}. However, when I use a = lens[1].getAttribute('price') in the browser console, it correctly displays the value as "0". Why is Vue showing ...

Endless Loop Issue with Google Maps API Integration in NextJS-React

Currently struggling to troubleshoot an infinite loop issue in my React function component map. I've spent a considerable amount of time analyzing the code and suspect that it might be related to the useEffects, but I'm unable to resolve it. Atta ...

Activate the Chrome Extension that allows you to open a link in a new tab with just a middle click or regular click, without closing the popup

When I try to click a link in my extension popup and open it in a new tab using "middle click -> open link in a new tab", the popup closes. Is there a way to keep the popup open so I can click on multiple links from my extension without interruption? Any ...

Trouble is arising in rendering events with years before 100 (specifically years 0000 - 0099) when using the ISO8601 format in fullCalendar

I've created a Calendar that showcases various events using fullcalendar. The events span from the years 0001 to 6000. Fullcalendar requires dates in ISO8601 format, and I am providing them as such. Events from the years 0100-6000 render perfectly w ...

Toggle the active class on the parent element when it is clicked

I'm encountering a problem with my JavaScript - attempting to make this function properly. Firstly, here is the desired functionality: 1.) Add or remove the 'active' class from the parent element when clicked 2.) When clicking inside the ...