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

A guide to efficiently reusing parameter definitions in functions using JSDoc

Currently, I have HTTP handlers set up in my express application. I want to use JSDoc annotations to document these handlers in a reusable manner. Here is what I currently have: /** * * @param {functions.Request} req * @param {functions.Response} res ...

Invoke another component to display within a React.js application

Click here to view the code snippet. I am facing an issue with my React components. I have component A that handles fetching and rendering a list, and I also have component B that accepts user input. How can I trigger component A from component B? It seem ...

The Vue Router hooks are not being activated within the component when utilizing Typescript

I've been pondering this issue for quite some time. Despite my extensive search efforts, I am still unable to figure out why the route-hooks are not working in my component: 1. The component is being loaded from RouterView: <router-view class="z1 ...

Launching various modals on marker click

I'm having an issue where I need a different modal to be displayed depending on the name in the markerSet array. Currently, the if/else statement is always returning the same modal. Take a look at the if statement in my JavaScript code below. The nam ...

display dynamic graphs using json data from a php backend

I'm having trouble displaying a graph using JSON data in Highcharts. Here is a sample of what I need: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-rotated-labels/ The file values ...

How to create a Bootstrap panel that collapses on mobile devices and expands on desktop screens?

Is there a simple way to remove the "in" class from the div with id "panel-login" when the screen size is less than 1199px (Bootstrap's xs, sm, and md modes)? I believe JavaScript or JQuery could be used for this, but I'm not very proficient in e ...

Vue Bootstrap Checkbox and <b-table> with <b-form-checkbox> components combine to provide a powerful and flexible user

I am currently implementing b-form-checkbox with b-table to fetch the selected module Ids. <b-table id="module-table" :items="list.modules" :fields="fields" :busy="isBusy"> <template slo ...

Avoiding overlapping in setTimeOut when using jQuery.hover()

Looking to trigger an effect one second after the page loads, and then every 3 seconds in a loop. When the user hovers over a specific element with the ID #hover, the effect should pause momentarily. It should then resume 2 seconds after the user stops hov ...

What is the best method for storing pug-formatted data in a database?

I am currently developing a JavaScript application where I utilize pug for templates and diskdb for storing data. Within my content, I have implemented pug syntax which may appear in the following format: p some content here p some more content here p: # ...

retrieving JSON data using ajax and processing it in PHP

I have some data that needs to be sent to the backend, and it looks like this: function view(){ let id = "12345678"; let profile = [{name:"dave", department : "Engineering"}, {name:"Tedd", ...

Setting the borderRadius for a web view on Android Maps V3: A complete guide

In my application, I am using Android Map V3 and have encountered a bug specific to the Kit-Kat version. The chromium kit throws up an error message - nativeOnDraw failed; clearing to background color, which prevents the map from being displayed. Despite ...

Utilizing Vue.js to retrieve database information and populate input fields through select options

In my Laravel 8 and Vue 3 application, I have a Student Component with a datalist that lists all the students. My goal is to populate the input fields with the specific student information when clicking on a student. I attempted to use Vue select, which i ...

Utilizing Selenium to locate an element by its class name and then deleting it from the document object model through

I have found a code that worked really well for me. It involves getting the quantity of messages first and then removing them from the DOM. public static void RemoveMessages() { // Removing messages from the DOM using JavaScript ...

The function of hasClass within an if statement appears to be malfunctioning

I'm struggling to figure out why my .hasClass function is not functioning correctly. I've implemented the Quick Search jQuery plugin, and below is the code I am using: <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.mi ...

I'm looking for assistance on how to execute a render right after making a put or delete request

class ProductApp extends Component { constructor() { super(); this.state = { currentProduct: null, items: [], }; this.handleUpdateSubmit= this.handleUpdateSubmit.bind(this); } componentDidMount() { axios.get('h ...

Leveraging IntersectionObserver to identify the video in view on the screen

Our Objective I aim to implement a swipe functionality for videos where the URL changes dynamically based on the ID of the currently displayed video. Challenges Faced Although I managed to achieve this with code, there is an issue where the screen flashe ...

Incorporating Button Value from Anchor Tag Title Upon Page Load

Currently, I am working on a real estate project and facing an issue with a contact modal box. My goal is to extract the title from tag "a" and place it as the button value in the modal box. English isn't my strong suit, so please excuse any errors i ...

Can one open a unique custom pop-up before the window is about to close?

Seeking a way to create a pop-up confirmation dialog for users when they try to log out or stay on the page while logged in. I attempted using the code below, but haven't been able to find the correct solution: window.onbeforeunload = function (e) { ...

Develop interactive, reusable custom modals using React.js

I am currently working on creating a reusable modal: Here is my component setup: class OverleyModal extends Component { constructor(props) { super(props); } openModal = () => { document.getElementById("myOverlay").style.display = "blo ...

Retrieving a variable within a try-catch statement

I am trying to implement a function: function collect_user_balance() { userBalance = 0; try { var args = { param: 'name'; }; mymodule_get_service({ data: JSON.stringify(args), s ...