When provided with two arrays, generate an object by pairing each element of the first array with the corresponding key from the second array

Despite trying countless times, I can't seem to figure out where I'm going wrong.

function userChecker(arr1,arr2) {

  let map = {};

  arr1.filter((user) => {

    arr2.filter((obj) => {


      if (user == obj.user) {
        map[user] = obj;
      } 
    
      else {
        map['untracked'] = [user];
      }


    });

  });

console.log(map)

}


userChecker([39471379, 44471379, 25471379, 35471379, 29471379,55471379],[{user: 39471379, salary: 250000}, {user: 44471379, salary: 260000}, {user: 35471379, salary: 148700},{user: 29471379, salary: 270500}]);

A function is needed that takes in two arrays: one containing user numbers and the other containing objects with employee data (user number and salary). The function should create an object where the user number is the key and the corresponding value is the object with all the data. // If an employee with a specific user number is not found, it means they do not work for the company. In such cases, a new entry must be created with the key being "untracked" and the value as an array of all user numbers that are not found.

Expected Output:

{39471379: {ID: 39471379, salary: 250000},
44471379: {ID: 44471379, salary: 260000},
35471379: {ID: 35471379, salary: 148700},
29471379: {ID: 29471379, salary: 270500},
"untracked": [25471379,55471379]}

Answer №1

To create a user data object with reduced user ids and retrieve specific data by cross-referencing the object.

function getFilteredUserData(users, data) {
    const ids = Object.fromEntries(data.map(obj => [obj.user, obj]));
    return users.reduce((result, user) => {
        if (ids[user]) result[user] = ids[user];
        else result.untracked.push(user);
        return result;
    }, { untracked: []});
}

const
    users = [39471379, 44471379, 25471379, 35471379, 29471379, 55471379],
    data = [{ user: 39471379,  salary: 250000 }, { user: 44471379, salary: 260000 }, { user: 35471379, salary: 148700 }, { user: 29471379, salary: 270500 }],
    filteredResult = getFilteredUserData(users, data);

console.log(filteredResult);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Implementing a strategy using a single loop, along with the usage of find.

const ids = [39471379, 44471379, 25471379, 35471379, 29471379,55471379];
const users = [{user: 39471379, salary: 250000}, {user: 44471379, salary: 260000}, {user: 35471379, salary: 148700},{user: 29471379, salary: 270500}];

function userCheck(ids, users) {
  
  // Initializing two arrays, one for tracked users and another for untracked users
  const output = [];
  const untracked = [];
  
  // Looping through the ids array
  for (const id of ids) {
    
    // Checking if there is a matching user based on id
    const foundUser = users.find(user => {
      return user.user === id;
    });
    
    // Adding the user object to output array if found
    if (foundUser) {
      output.push({ [id]: foundUser });
    
    // Otherwise adding the id to the untracked array
    } else {
      untracked.push(id);
    }
  }
  
  // Combining the tracked and untracked arrays and returning them 
  return [...output, { untracked }];
}

console.log(userCheck(ids, users));

For more information, refer to:

Answer №3

My approach involved utilizing a forEach loop in conjunction with the find() method.

const ids = [39471379, 44471379, 25471379, 35471379, 29471379,55471379];
const users = [{user: 39471379, salary: 250000}, {user: 44471379, salary: 260000}, {user: 35471379, salary: 148700},{user: 29471379, salary: 270500}];
    function checkUsers (ids, users) {
        let resultObject = {};
        resultObject["untracked"] = [];
        console.log(resultObject);
    
        ids.forEach(element => {
            const id = element;
            const foundUser = users.find(ele => ele.user === element);
            if(foundUser) {
                resultObject[id] = {
                    [id] : foundUser
                }
            } else {
                resultObject["untracked"].push(id);
            }
        });
        return resultObject;
    
    const finalResult = checkUsers(ids, users);
    console.log(finalResult);

Answer №4

To generate an o object from the data array with a specific format for all users, you can utilize the Array.prototype.reduce() method to populate properties that will be spread across the result object using the Spread syntax (...). Lastly, for handling untracked, you only need to employ the Array.prototype.filter() function once to filter out the ids from the users array that are absent in the properties of the o object.

Snippet:

const users = [39471379, 44471379, 25471379, 35471379, 29471379, 55471379]
const data = [{ user: 39471379, salary: 250000 },{ user: 44471379, salary: 260000 },{ user: 35471379, salary: 148700 },{ user: 29471379, salary: 270500 }]

const userCheck = (users, data) => {
  const o = data.reduce((a, c) => (a[c.user] = c, a), {})
  return {
    ...o,
    untracked: users.filter(user => !o[user])
  }
}

console.log(userCheck(users, data))
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Updating the Bootstrap entry dynamically within the @NgModule module

My web application has a specific requirement where it can only be accessed through example.com/index.html without any parameters. The backstory behind this restriction is quite lengthy, so let's not delve into that. Within the index.html file, I have ...

Building a Node.js view to display an OpenLayers map

I'm new to working with node.js and am currently trying to incorporate an OpenLayers map onto a webpage. However, I'm facing an issue where the map is not displaying as expected. Code: app.js var express = require('express'); var ap ...

Passing a dynamic 2-dimensional array into a function in C: Best practices

I am looking for a solution to dynamically allocate a 2-dimensional array in a function that has 'n' rows and 'm' columns, with the values also read from an 'input' function. int main() { int** matrix; int n, m; in ...

Can React avoid re-rendering if the setState does not impact the rendering process?

For example, let's consider a scenario where a hook is used to make an API request: function useApi(...) { const [state, setState] = useState({ fetching: false }); useEffect(() => { setState({ fetching: true }); fetch(...) .then( ...

What are the steps for releasing a collection of Vue.js components?

Currently, I am working on a project that involves a Vuex module and abstract components that users can extend. My goal is to clean up my codebase by separating this project into a well-tested module and publishing it on NPM. In order to achieve this, I ha ...

Guide on how to display registration form data on the current page as well as on a separate page

I am facing an issue with outputting registration form data to two different pages after successful validation. Specifically, I want the form data to be displayed on both the current page (form.php) and another page (profile.php). Despite my efforts to fin ...

Although qsort is utilized within the struct, the resulting struct appears disorganized and chaotic

Trying to utilize qsort to sort an array of struct by name, but the resulting output is unexpected. typedef struct node{ char name[64]; char ingredient[10][64]; }node; int compare(const void *a, const void *b){ node *nodeA = (node *)a; nod ...

Utilizing AJAX within an Ember.RSVP.Promise

I'm curious about the necessity of using the "return" keyword in the common code snippet below when invoking AJAX requests. Specifically, is it necessary for the $.ajax function (considering that $.ajax already returns a promise), or does it serve ano ...

How to automatically open JQuery Accordion panels when the page loads

My Accordion loads with the 1st panel open upon page load, but I am looking for a way to have the entire Accordion closed by default. Any help or suggestions on how to achieve this would be highly appreciated. Thank you for your assistance. FIDDLE http:// ...

"Encountering challenges with integrating Addthis on a WordPress website

Hey there, I've got a few questions about my self-hosted Wordpress site... 1) I'm having an issue with the Google Plus button not appearing on AddThis Smart Layers. Even though the code is in my header, only 4 buttons show up on my page - the Go ...

Navigating the loading of information with fetch and React Hooks

As a newcomer to React and still learning JavaScript, I am facing a challenge with handling useEffect alongside an asynchronous function. My goal is to fetch data from an API and render a quote in the paragraph with id of text, along with the author's ...

How to retrieve a subset from a multidimensional array in PHP

Here is a simplified version of my multidimensional array: [1] => Array ( [id] => 1 [id1] => 0 ) [2] => Array ( [id] => 2 [id1] => 0 [children] => Array ( ...

Unable to create the complete PDF file using html-pdf in a NodeJS environment

When trying to create a PDF from an HTML template, I am encountering some difficulties. While it works with static entries, I want to generate the PDF for multiple items that can vary each time. I feel like I might be overlooking something, so any suggesti ...

Tips for transferring PHP variables into JavaScript variables?

Using PHP variables fetched from a database to populate JavaScript variables is an essential task that needs to be done. One way to achieve this is by defining JavaScript variables as shown in the code example below: var oMain = new CMain({ mon: <?p ...

The .each function in JavaScript is creating conflicts with other classes on the webpage

HTML <ul class="courseDates"> <li class="dateOne col-sm-2"> {tag_course date 1} </li> <li class="dateTwo col-sm-2"> {tag_course date 2} </li> <li class="dateThree col-sm-2"> { ...

React - optimize performance by preventing unnecessary re-renders of an object property

In my current project, I am working with an auction object that has two properties: remainingTime and amount. To enhance user experience, I integrated a countdown timer using the react-countdown-now library to display the remainingTime. Additionally, there ...

Understanding Multiple Type Scenarios in React with Typescript

Code Demonstration: type PropsType = {top: number} | {bottom: number} // The function that moves something in one direction by a specific distance. function move(props: PropsType) { ... } Expected Usage: move({top: 100}) or move({bottom: 100}) Avoid us ...

Updating multiple documents in Mongoose that have a specific element in an array

I have structured a Mongoose schema like this: const mongoose = require('mongoose'); const ItemSchema = mongoose.Schema({ id: { type: String, required: true, }, items: { type: Array, required: true, }, date: { type: ...

HTML does not have full support for the Arabic language

I am currently working on a project that needs to be converted into Arabic. I am utilizing codeigniter. However, when I attempt to write Arabic in HTML, it displays as (?????) for Arabic characters. Below is my HTML code: <!DOCTYPE HTML PUBLIC "-//W3C ...

Is it necessary to remove every letter before moving on to the following array position?

I've been working on a script to create an animated "self-writing text" effect. However, I'm encountering an issue where each word jumps to the next one instead of smoothly transitioning by deleting each letter before moving on to the next word i ...