Comparing two arrays with field in common then pushing to a new array with corresponding grouped fields

array of objects javascript
javascript multidimensional array
javascript array
how to access array of objects in javascript
javascript array of arrays
javascript map
object inside array javascript
javascript array of objects push

general programming problem here.

I have this array called SPACES

[
  {
    _id: 5e1c4689429a8a0decf16f69,
    challengers: [
      5dfa24dce9cbc0180fb60226,
      5dfa26f46719311869ac1756,
      5dfa270c6719311869ac1757
    ]
  },
  {
    _id: 5e1c4eb9c9461510407d5e81,
    challengers: [ 5dfa24dce9cbc0180fb60226, 5dfa26f46719311869ac1756 ],
  }
]

And this array called USERS

[
  {
    _id: 5dfa24dce9cbc0180fb60226,
    name: 'Account 1',
    email: 'account1@gmail.com',
    spaces: [ 5e1c4689429a8a0decf16f69, 5e1c4eb9c9461510407d5e81 ],
  },
  {
    _id: 5dfa26f46719311869ac1756,
    name: 'Account 2',
    email: 'account2@gmail.com',
    spaces: [ 5e1c4689429a8a0decf16f69, 5e1c4eb9c9461510407d5e81 ]
  },
  {
    _id: 5dfa270c6719311869ac1757,
    name: 'Account 3',
    email: 'account3@gmail.com',
    spaces: [ 5e1c4689429a8a0decf16f69 ]
  }
]

What I want to do, is go through both, and instead of having the SPACES.challengers array be just IDS, I would like the array to contain each USER object.

So for example, if the USER has an ID that is inside the SPACES.challengers array, then push the user into that array (which will then be the entire object).

SO FAR I have tried this (I am not very good yet):

 users.map( ( user ) => {
          spaces.map( ( space ) => {
              if ( user.spaces.includes( space._id ) ) {
                       space.challengers.push(user)
                  }
             } );
        } );

However, I am not getting inside the IF block. (Even if I did, not sure if it would work OR if this is even how to do it). It feels Odd doing double maps, as I get so many iterations, and it duplicates my push (cause I have no logic to see if it just has been pushed).

.map and .find should work here. keep it simple.

var spaces = [
    {
      _id: "5e1c4689429a8a0decf16f69",
      challengers: [
        "5dfa24dce9cbc0180fb60226",
        "5dfa26f46719311869ac1756",
        "5dfa270c6719311869ac1757"
      ]
    },
    {
      _id: "5e1c4eb9c9461510407d5e81",
      challengers: ["5dfa24dce9cbc0180fb60226", "5dfa26f46719311869ac1756", "some non existent"]
    }
  ],
  users = [
    {
      _id: "5dfa24dce9cbc0180fb60226",
      name: "Account 1",
      email: "account1@gmail.com",
      spaces: ["5e1c4689429a8a0decf16f69", "5e1c4eb9c9461510407d5e81"]
    },
    {
      _id: "5dfa26f46719311869ac1756",
      name: "Account 2",
      email: "account2@gmail.com",
      spaces: ["5e1c4689429a8a0decf16f69", "5e1c4eb9c9461510407d5e81"]
    },
    {
      _id: "5dfa270c6719311869ac1757",
      name: "Account 3",
      email: "account3@gmail.com",
      spaces: ["5e1c4689429a8a0decf16f69"]
    }
  ],
  result = spaces.map(({ _id, challengers }) => ({
    _id,
    challengers: challengers.map(challenger =>
      users.find(user => user._id === challenger)
    ).filter(row => row)
  }));

  console.log(JSON.stringify(result, null, 2));

Data Structures: Objects and Arrays :: Eloquent JavaScript, Both string and array values contain, in addition to the length property, A stack, in programming, is a data structure that allows you to push values into it and pop into a single value and then put those grouped values into an array of log entries. This kind of loop is common in classical JavaScript—going over arrays one� New Delhi, Delhi, India 2 Comparing two arrays with field in common then pushing to a new array with corresponding grouped fields Jan 14.

Assuming every entry in the Users array has a unique ID, we can build a Hashmap to store (id, index) pairs in order to search efficiently for an ID from Users array while looping through Spaces array.

let spaces = [{_id: '5e1c4689429a8a0decf16f69',challengers: ['5dfa24dce9cbc0180fb60226', '5dfa26f46719311869ac1756', '5dfa270c6719311869ac1757']},{_id: '5e1c4eb9c9461510407d5e81',challengers: [ '5dfa24dce9cbc0180fb60226', '5dfa26f46719311869ac1756' ],}]

let users = [{_id: '5dfa24dce9cbc0180fb60226',name: 'Account 1',email: 'account1@gmail.com',spaces: [ '5e1c4689429a8a0decf16f69', '5e1c4eb9c9461510407d5e81' ],},{_id: '5dfa26f46719311869ac1756',name: 'Account 2',email: 'account2@gmail.com',spaces: [ '5e1c4689429a8a0decf16f69', '5e1c4eb9c9461510407d5e81' ]},{_id: '5dfa270c6719311869ac1757',name: 'Account 3',email: 'account3@gmail.com',spaces: [ '5e1c4689429a8a0decf16f69' ]}]

let IDIndexMapping = {} // To store (_id, index) pairs, in order to improve search efficiency

for(let index in users) // Iterate through Users array using index
    IDIndexMapping[users[index]._id] = index; // store (_id, index) pair in IDIndexMapping

// I'm avoiding using `map` and using vanilla `for` loop for space efficiency
// as map returns a new array but with `for` loop, we can perform changes in-place

for(let outerIndex in spaces){ // Iterate through `spaces` array using index
    let challengers = spaces[outerIndex].challengers; // Get challengers array
    for(let innerIndex in challengers){ // Iterate through challengers array using index
        let ID = challengers[innerIndex]; // Get ID
        if(ID in IDIndexMapping) // If ID exists in IDIndexMapping
            spaces[outerIndex].challengers[innerIndex] = users[IDIndexMapping[ID]]; // Change ID to actual User object
    }
}
console.log(spaces)

Output

[ { _id: '5e1c4689429a8a0decf16f69',
    challengers: [ [Object], [Object], [Object] ] },
  { _id: '5e1c4eb9c9461510407d5e81',
    challengers: [ [Object], [Object] ] } ]

Indexed collections, This includes arrays and array-like constructs such as Array objects and TypedArray This means that the length property will be one more than the highest index stored in the array: A common operation is to iterate over the values of an array, concat() joins two or more arrays and returns a new array. readArray() will read array of 5 elements. printArray() will print array of 5 elements. compareArray() will compare elements of both of the array elements and returns 0 if all elements are equal otherwise function will return 1. C program (Code Snippet) - Compare Two Arrays. Let’s consider the following example:

You can create a map of challengers for look-up and then put them in spaces.

//create user map for look-up

userMap = users.reduce((res, val) => ({
  ...res,
  [val._id]: val
}), {});

//change challenger id with user object

inflatedSpaces = spaces.map(s => ({ ...s, challengers: s.challengers.map(c => userMap[c]) }));

array_diff - Manual, Returns an array containing all the entries from array1 that are not present in any of Also, if the two arrays contain a different number of values, then which If you need compare two arrays of integers or strings you can use such function: One common caveat of this function is that if the arrays match, an empty array is� Given two arrays arr1[] and arr2[], we need to combine two arrays in such a way that the combined array has alternate elements of both. If one array has extra element, then these elements are appended at the end of the combined array.

You could map the users with a Map.

Beside the destructuring of the object for mapping this answer uses for this part

challengers: challengers.map(
    Map.prototype.get,                  // cb with a prototype and using `this`
    new Map(users.map(o => [o._id, o])) // thisArg
)

the above mentioned Map in two parts.

The lower part generates an instance of Map where _id of the users items is used as key and the whole object as value. This instance is uses as thisArg of Array#map, the second parameter.

The upper part is a prototype of Map, used as callback. And while an this object is supplied, a binding (Function#bind) is not necessary.

var spaces = [{ _id: '5e1c4689429a8a0decf16f69', challengers: ['5dfa24dce9cbc0180fb60226', '5dfa26f46719311869ac1756', '5dfa270c6719311869ac1757'] }, { _id: '5e1c4eb9c9461510407d5e81', challengers: ['5dfa24dce9cbc0180fb60226', '5dfa26f46719311869ac1756'] }],
    users = [{ _id: '5dfa24dce9cbc0180fb60226', name: 'Account 1', email: 'account1@gmail.com', spaces: ['5e1c4689429a8a0decf16f69', '5e1c4eb9c9461510407d5e81'] }, { _id: '5dfa26f46719311869ac1756', name: 'Account 2', email: 'account2@gmail.com', spaces: ['5e1c4689429a8a0decf16f69', '5e1c4eb9c9461510407d5e81'] },{ _id: '5dfa270c6719311869ac1757', name: 'Account 3', email: 'account3@gmail.com', spaces: ['5e1c4689429a8a0decf16f69'] }],
    result = spaces.map(({ _id, challengers }) => ({
        _id,
        challengers: challengers.map(
            Map.prototype.get,
            new Map(users.map(o => [o._id, o]))
        )
    }));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Array Functions - Manual, array_change_key_case — Changes the case of all keys in an array the difference of arrays using a callback function on the keys for comparison in an array; array_push — Push one or more elements onto the end of array Searches the array for a given value and returns the first corresponding key if New array : A simple way is to run a loop and compare elements one by one. Java provides a direct method Arrays.equals () to compare two arrays. Actually, there is a list of equals () methods in Arrays class for different primitive types (int, char,..etc) and one for Object type (which is base of all classes in Java).

Javascript group array of objects by date, resolvedOptions() Returns a new object with properties reflecting the locale and Two Date objects should be in the same array if year AND month match up. array should load existing value values from hidden field and then should get In fact, you can even sort arrays that contain RFC 8259 JSON December 2017 8. NumPy Array Object Exercises, Practice and Solution: Write a NumPy program to find common values between two arrays.

Working with Arrays | Cloud Spanner, In Cloud Spanner SQL, an array is an ordered list consisting of zero or more the ARRAY elements, and then the CROSS JOIN joins this new set of rows with the You can also flatten ARRAY type fields of STRUCT values. but does represent a common way to get information from a repeated field. GROUP BY name; Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though. Note : If there are repetitions, then counts of repeated elements must also be same for two array to be equal.

d3/d3-array: Array manipulation, ordering, searching , Methods for transforming arrays and for generating new arrays. # d3.group( iterable, keys) � Source, Examples. Groups the specified iterable of values into a Map� Add two numbers represented by two arrays Last Updated: 30-01-2019 Given two array A[0….n-1] and B[0….m-1] of size n and m respectively, representing two numbers such that every element of arrays represent a digit.

Comments
  • Is every entry in the Users array has a unique ID? If yes, a hashmap can be built out of this array to search easily (and faster) for an ID while looping through challengers array inside Spaces array.
  • This returns the challenger array as undefined items (in the result variable)
  • you will need to do some null checks if some ids doesn't exist
  • I did that, and when consoling something, I get the correct result. When returning user, still get undefined. ``` result = spaces.map( ( { _id, challengers } ) => ({ _id, challengers: challengers.map( challenger => { users.find( ( user ) => { if ( user._id === challenger ) { return user; } } ); } ) }) ); @Ashish Modi
  • @CevinThomas I have added a non existent id in input and handled that using filter. updated the code. see if that helps.
  • filters out the null of undefined. filter(row => row) id equal to if(row) which basically filter out null or undefined values
  • Looks very interesting, could you walk me through a little bit of the thought process behind the code and what it does? I have yet to see a complex map manoeuvre like this. Thank you!