Sort through an array of objects by their respective values within another array of nested objects

I am struggling to filter out positions from the positions array that are already present in the people array.

Despite trying different combinations of _.forEach and _.filter, I can't seem to solve it.

console.log(position)

var test = _.filter(position, function(pos) {
    _.forEach(people, function(peo) {
        _.forEach(peo.position, function(peoplePos) {
            if(peoplePos.value == pos.value){
                return false;
            }
        });
    });
});

console.log(test)

The main issue here is that the positions are nested within each object in the people array.

var positions = [{
    val: 'CEO',
    label: 'CEO XXX'
}, {
    val: 'CTO',
    label: 'CTO XXX'
}, {
    val: 'CBO',
    label: 'CBO XXX'
}, {
    val: 'CLO',
    label: 'CLO XXX'
}]

var people = [{
    id: 'AAA',
    positions: [{
        val: 'CEO',
        label: 'CEO XXX'
    }]
},{
    id: 'BBB',
    positions: [{
        val: 'CXO',
        label: 'CXO XXX'
    },{
        val: 'CEO',
        label: 'CEO XXX'
    }]
},{
    id: 'CCC',
    positions: [{
        val: 'CTO',
        label: 'CTO XXX'
    }]
}]

In this case, the desired outcome would be:

var positions = [{
    val: 'CBO',
    label: 'CBO XXX'
}, {
    val: 'CLO',
    label: 'CLO XXX'
}]

This is because CBO and CLO are not represented in any object within the people array.

Answer №1

A convenient method is to convert both the array of people into strings and then compare their positions within the string.

By doing this, you can avoid the need to iterate through a nested data structure.

var positions = [{ val: 'CEO', label: 'CEO XXX' }, { val: 'CTO', label: 'CTO XXX' }, { val: 'CBO', label: 'CBO XXX' }, { val: 'CLO', label: 'CLO XXX' }]

var people = [{ id: 'AAA', positions: [{ val: 'CEO', label: 'CEO XXX' }] }, { id: 'BBB', positions: [{ val: 'CXO', label: 'CXO XXX' }, { val: 'CEO',
    label: 'CEO XXX' }] }, { id: 'CCC', positions: [{ val: 'CTO', label: 'CTO XXX' }] }];

var stringifiedPeople = JSON.stringify(people)

var newPositions = positions.filter((position) =>
  !stringifiedPeople.includes(JSON.stringify(position))
);

console.log(newPositions)

Alternatively, you could construct a map containing all filled positions and then identify available positions by filtering them out.

var positions = [{ val: 'CEO', label: 'CEO XXX' }, { val: 'CTO', label: 'CTO XXX' }, { val: 'CBO', label: 'CBO XXX' }, { val: 'CLO', label: 'CLO XXX' }]

var people = [{ id: 'AAA', positions: [{ val: 'CEO', label: 'CEO XXX' }] }, { id: 'BBB', positions: [{ val: 'CXO', label: 'CXO XXX' }, { val: 'CEO',
    label: 'CEO XXX' }] }, { id: 'CCC', positions: [{ val: 'CTO', label: 'CTO XXX' }] }];

var mappedPositions = {}

people.forEach((p) =>
  p.positions.forEach((position) =>
    mappedPositions[position.val] = true
  )
);

var newPositions = positions.filter((position) => !mappedPositions[position.val]);

console.log(newPositions)

Answer №2

If you want to only include objects in the people array that match specific positions from the positions array, you can utilize JavaScript's filter, find, and some methods.

var positions = [{val:'CEO',label:'CEOXXX'},{val:'CTO',label:'CTOXXX'},{val:'CBO',label:'CBOXXX'},{val:'CLO',label:'CLOXXX'}];
var people = [{id:'AAA',positions:[{val:'CEO',label:'CEOXXX'}]},{id:'BBB',positions:[{val:'CXO',label:'CXOXXX'},{val:'CEO',label:'CEOXXX'}]},{id:'CCC',positions:[{val:'CTO',label:'CTOXXX'}]}];

const filteredPositions = positions.filter(position => {
  return !people.find(person => {
    return person.positions.some(({ val, label }) => {
      return val === position.val && label === position.label;
    });
  });
});

console.log(filteredPositions);

Answer №3

Explanation of my approach.

The code can be optimized further by using a single .reduce() function on the positions array for improved efficiency. However, I have chosen to present the steps individually to provide clarity on the purpose of each step.

var positions = [{val:'CEO',label:'CEOXXX'},{val:'CTO',label:'CTOXXX'},{val:'CBO',label:'CBOXXX'},{val:'CLO',label:'CLOXXX'}];

var people = [{id:'AAA',positions:[{val:'CEO',label:'CEOXXX'}]},{id:'BBB',positions:[{val:'CXO',label:'CXOXXX'},{val:'CEO',label:'CEOXXX'}]},{id:'CCC',positions:[{val:'CTO',label:'CTOXXX'}]}];

const occupied_positions = people
  .map( person => person.positions )
  .flat()
  .map( position => position.val );
  
const all_positions = positions
  .map( position => position.val );
  
const open_positions = all_positions
  .filter( position => !occupied_positions.includes( position ))
  .map( position => positions.find( source => source.val === position ));
  
console.log( open_positions );

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

Strangely compressed HTML image

I am facing an issue with using a base64-encoded png retrieved from a server in WebGL. To incorporate the encoded png, I load it into an html Image object. For my specific needs, it is crucial that the png data remains completely lossless, however, I&apos ...

A guide on getting the `Message` return from `CommandInteraction.reply()` in the discord API

In my TypeScript code snippet, I am generating an embed in response to user interaction and sending it. Here is the code: const embed = await this.generateEmbed(...); await interaction.reply({embeds: [embed]}); const sentMessage: Message = <Message<b ...

How can I use a string argument in JavaScript to sort an array of objects by that specific value?

Currently, I am implementing React and facing a challenge with creating a reusable sorting component. This component is meant to sort an array of objects based on a specific property field. For instance, imagine having an array of objects with properties a ...

Challenge with JavaScript personalized library

No matter how many times I review my code, I find myself perplexed. Despite my efforts to create a custom library of functions from scratch (shoutout to stackoverflow for guiding me on that), the results are leaving me puzzled. A javascript file is suppose ...

Utilizing $.Deferred() in a loop of nested ajax requests

I have spent countless hours searching for solutions to my problem, but I am still hopeful that someone out there has a solution. The issue at hand is being able to receive a notification once function a() has finished its execution. The challenge lies in ...

Capturing all requests - javascript

I have a webpage called sample-page.html that contains 2 links: sample-page.html - link1 (GET, AJAX) - link2 (GET, new page) Clicking on link1 triggers an AJAX GET request and remains on the same page (sample-page.html). Clicking on l ...

Associating data with controller upon click event

My application displays a tab full of objects for the user to choose from by clicking on any line. Once they make their selection, I need to send specific data related to that object to the server. This is what the interface looks like: https://i.sstatic ...

How to effectively create factories in AngularJS

I stumbled upon this angularjs styleguide that I want to follow: https://github.com/johnpapa/angular-styleguide#factories Now, I'm trying to write my code in a similar way. Here is my current factory implementation: .factory('Noty',functi ...

The interaction between a JavaScript function call and C# is not functioning properly

Attempting to invoke the JavaScript function from CodeBehind ( C# ) : function scrollToBottom() { window.scrollTo(0, document.body.scrollHeight); } The function successfully executes when directly called from my asp.net application. However, ...

Revamping ng-model in AngularJS

Here is my scenario: cols = [{field="product.productId"},{field="product.productPrice"}]; data = {products:[{product:{productId:1,productPrice:10}, {product:{productId:2, productPrice:15}}]} This is what I want to achieve: <div ng-repeat="product in ...

When should the grecaptcha.execute() function be invoked while utilizing Invisible reCAPTCHA V2?

I recently implemented invisible reCAPTCHA successfully, but I'm wondering if I did it correctly when calling grecaptcha.execute(). After loading the API script with an explicit call like this: <script src="https://www.google.com/recaptcha/api.js ...

What is the location where nvm saves its node.js installations?

I'm having trouble locating where node.js installations are stored after downloading and installing through commands like: nvm install 5.0 Can anyone provide some insight on this? ...

Exploring the synergies between Angular Dragula and utilizing the $index property

Currently, I have implemented an ng-repeat of rows that can be rearranged using Angular Dragula. Despite successful drag-and-drop functionality, the $index in ng-repeat remains constant for each item even after reordering. The screenshot below depicts the ...

Implementing authorization middleware using Express.js in Ajax

My app has a straightforward authorization middleware that functions flawlessly with regular GET and POST requests. However, when I send a POST request via AJAX, the middleware fails to redirect to a 401 page and instead bypasses it, allowing the data to b ...

Executing Grunt: Setting up a dual Connect and Express server to operate on one port

I'm still fairly new to Grunt and I've been wondering if it's possible to run both servers on the same port simultaneously. I seem to be encountering some issues with this setup, most likely stemming from the Grunt file. I am utilizing grun ...

Unable to call a basic object's prototype method

Just starting out with node and feeling like I might be overlooking something simple. In my model file, I have a class that creates new object instances in the following way: const mongodb = require('mongodb'); const getDb = require('../util ...

Detect errors in the `valueChanges` subscription of Firestore and attempt a retry if an error occurs

My Angular app utilizes Firestore for storing data. I have a service set up to retrieve data in the following way: fetchCollectionColors(name) { this.db.collectionGroup('collection-colors', ref => ref.where('product', '==&ap ...

Having Trouble with Shopify's Asynchronous Ajax Add to Cart Feature?

I have developed a unique Shopify page design that allows users to add multiple items to their cart using Shopify's Ajax API. I've created a test version of the page for demonstration: Below is the current javascript code I am using to enable as ...

Issue with border-color in CSS on Chrome tables

Here is a table style I have defined for selected elements: tr[selected] { background: #FFF; border-color: #000000; color: #000000; } To apply this style, I use JavaScript: $this.unbind().change(function () { element = $(this).parent ...

The Node.js Express undefined callback function is causing issues

I'm currently working on a personal project and I don't have much experience with nodeJS. My goal is to retrieve remote JSON data, generate statistics based on that data, and display it. However, I am encountering some issues with the callback fu ...