Iterate through a collection of nested objects and check them against an object contained within an array

I'm facing a frustrating issue in Firebase where I am required to compare an object returned to me with an array.

I need assistance in completing this method:

const removeAlreadySeenUsersFromQueue = (newUsers, likedUsers) => {

}

The scenario is that newUsers is an array of objects, each containing an id of interest.

On the other hand, likedUsers is returning as an array of objects within objects, like so:

[{object1: {}, object2: {}, object3: {}]
, essentially an array of length one. Within each object, there exists an id key that I need to identify. My goal is to compare both arrays and return an array solely containing objects whose ids appear only in newUsers and not in likedUsers. I believe object.keys() might be useful here, but my current attempts are unsuccessful

For example:

[{id: 4444}, {id: 5555}, {id: 6666}]

[{object1: {id: 4444}, object2: {id: 5555}, object3: {id: 121241}}]

After comparing these two arrays, I expect to receive just {id: 6666}.

Answer №1

This code snippet is designed to handle multiple matches by filtering out elements from one array that match certain criteria in another array. For demonstration purposes, an additional object with the id value of 7777 has been added to the first input array.

// Input arrays
var array1 = [{id: 4444}, {id: 5555}, {id: 6666}, {id: 7777}];
var array2 = [{object1: {id: 4444}, object2: {id: 5555}, object3: {id: 121241}}];

// Output array after filtering
var newArray = array1.filter(function(obj) {
    // Assume the element from array1 should be added by default
    var includeElement = true;

    // Check if the element from array1 exists in array2 and update includeElement accordingly
    Object.keys(array2[0]).forEach(function(key) { 
        if (array2[0][key].id == obj.id)     
            includeElement = false; 
    });

    // Complete the filter function by returning whether to include the element or not
    return includeElement;
});

// Log the filtered output array
console.log(newArray);

Answer №2

To retrieve the ids, you can utilize the reduce method and then apply the filter function in combination with the some function.

The result of the reduce operation may contain duplicate elements like [666, 555, 666, 777], but this scenario is not considered since your example does not involve repeated ids.

var source = [{ id: 4444 }, { id: 5555 }, { id: 6666 }, { id: 123456 }];
var content = [{ object1: { id: 4444 }, object2: { id: 5555 }, object3: { id: 121241 }}];

var ids = content.reduce((acc, curr) => [...acc, ...Object.keys(curr).map((k) => curr[k].id)] , []);

var result = source.filter((e) => {
  return !ids.some((c) => {
    return e.id === c;
  });
});

console.log(result);

Resources

Answer №3

Did you mention that your array has a length of 1? So, essentially, you're referring to something like [{}]? Why not consider changing it to [{}, {}, {}] and then looping through it using the for (element of array) - for of loop. Alternatively, if you prefer having all elements within one object, you can iterate over it using a for in loop by going with for (element in array[0]).

UPDATE Upon seeing your example, I've come up with this snippet:

const firstArray = [{id: 4444}, {id: 5555}, {id: 6666}];
const secondArray = [{object1: {id: 4444}, object2: {id: 55555}, object3: {id: 121241}}];

for (let object in secondArray[0]) {
   if (firstArray.some(el => el.id === secondArray[0][object].id)} {
      //perform some action
   }
}

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

How can you create a basic slideshow without relying on jQuery to cycle through images?

Imagine you have a div containing 3 images. Is there a way to build a basic slideshow that smoothly transitions between the images, showing each one for 5 seconds before moving on to the next one and eventually looping back to the first image without rely ...

Error: Trying to access 'whenReady' property of undefined variable is not allowed

As a beginner in electron app development, I am facing an issue when running npm start from the terminal. The error message I receive is: TypeError: Cannot read properties of undefined (reading 'whenReady')... This specific problem seems to be ...

Creating an ImmutableJS Record with custom types: A step-by-step guide

Is there a way to make ImmutableJS Records throw runtime exceptions if fields are missing instead of needing default values? ...

Here's a guide on how to package and send values in ReactJs bundles

I'm currently involved in a ReactJs project that does not rely on any API for data management. For bundling the React APP, we are using Webpack in the project. The challenge now is to make the React APP usable on any website by simply including the ...

A guide to presenting array data retrieved from an Ajax call within HTML using Laravel 4.1

I have an AJAX call to a controller that returns array data to my view. I want to display this array data in HTML upon clicking, but I'm not sure how to do it yet. Here's what I have so far: AJAX Call: request = $.ajax({ url: "/fans/ ...

Creating a file logging system with log4js to capture Console logs

Is there a way to automatically log all console logs, including failed expectations and exceptions, to a file without using try and catch in JavaScript? In Java's LOG4j, the rootlogger feature does this by default. Is there a similar functionality ava ...

Executing Javascript within an iframe

Is there a way to include a script in an iframe? I came up with the following solution: doc = $frame[0].contentDocument || $frame[0].contentWindow.document; $body = $("body", doc); $head = $("head", doc); $js = $("<script type='text/javascript&a ...

Getting Rid of Angular Material Suggestions: A Step-by-Step Guide

<md-autocomplete ng-model="ctrl.searchText" md-selected-item="ctrl.selectedItem" md-selected-item-change="ctrl.selectedItemChange(item)" md-search-text="ctrl.searchText" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" ...

CSS-enabled tabs built with React

Currently, I have a setup with 5 divs and 5 buttons where only one div is visible at a time when its corresponding button is clicked. However, I am looking for suggestions on how to improve the efficiency and readability of my code. If you have any best pr ...

After a two-second period of inactivity, the buttons on the item should trigger an action

I have a scenario in mind that I want to implement: When the user clicks on either the "Plus" or "Minus" button. If the user doesn't click on any of those buttons within 2 seconds, then we assume that the current quantity should be sent to the server ...

Employ the 'this' attribute within _.map

I am facing an issue where I need to call a setState function within a _.map loop in React. However, the loop is losing the reference to 'this' and therefore I cannot use setState as this becomes undefined. cargaDinamica(){ _.map(this.stat ...

Creating dynamic routes in express to enable flexible and customizable paths

Exploring the dynamic usage of paths in Express has been on my mind. Specifically, I have been employing lodash to locate a path in a separate file using regex methods. routes.js const json = require('./routes.json') const _ = require('l ...

Retrieving the chosen value when there is a change in the select tag

Building a shop and almost done, but struggling with allowing customers to change product quantities in the cart and update prices dynamically. I've created a select-tag with 10 options for choosing quantities. I'd like users to be able to click ...

Bring in solely the static variable from an ES6 module

I have a file called common.js which holds all the necessary variables and methods used in my App, including a nav-bar module (nav-bar.js) among others. Typically, every module in my app will import the entire common.js module, except for the login module ...

Navigating the reactive array in Vue 3 with finesse

Currently, I'm facing some challenges with my Vue 3 app in terms of getting things to work as expected. The main issue lies in properly accessing a reactive array. Let me provide you with the code for better comprehension: Within my global store sto ...

Exploring IP geolocation integration within Rails 3

I am looking to add a dynamic feature to my homepage that will display the location object closest to the reader's physical location. Currently, I have a Location model with longitude and latitude fields. My goal is to retrieve the location model obj ...

Select Items Based on Filtering Arrays

Within the JSON format below, there exists a state in addition to a checkbox state that signifies the selection of categories. initialData = [ { store_name: 'Shop 1', women: false, men: false, kids: true}, { store_name: 'Shop ...

Is there a way to run /_next/static/xxx.js using a script tag?

I have customized my next.config file (webpack) to generate a static JavaScript file (.next/static/loader.js). The original loader.js is an Immediately Invoked Function Expression (IIFE): (function stickerLoader(){ alert('Hello'); // ... so ...

Is there a way to acquire and set up a JS-file (excluding NPM package) directly through an NPM URL?

Is it feasible to include the URL for the "checkout.js" JavaScript file in the package.json file, rather than directly adding it to the Index.html? Please note that this is a standalone JavaScript file and not an NPM package. The purpose behind this appr ...

Angular sing ng-view to load images from a file

I am developing a single page app (index.html) with the following relevant sections: <!DOCTYPE html> <html> <head> <base href="/mi_ui/"> <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css"> <script s ...