skip to Main Content

I try to do compare two array object and add new data to first array if id is match using below code but it is not working

first array sample :

first array
{
  name :'sachin',
  id :1 
},
{
  name :'dravid',
  id :2 
},
{
  name :'ganguly',
  id :3 
}

second array sample
second array

{
  score :186,
  id :1 
},
{
  score :145,
  id :2 
},
{
  score :183,
  id :3 
}

result array

result array :

{
  name :'sachin',
  highest :186,
  id :1 
},
{
  name :'dravid',
  highest :145,
  id :2 
},
{
  name :'ganguly',
  highest :183,
  id :3

}

code i have tried to compare first and second array to check id is match.

 let result = firstData.map(item => {
         if (secondData && secondData.some(secondItem => secondItem.id === item.id)) {
           return {
             ...item,
             highest: secondItem.score
           };
         } else {
           return {
             ...item,
             highest: ''
           };
         }
       }); 
       console.log("result",result);

3

Answers


  1. You are taking data from the second array incorrectly. You can do something like this:

    let result = firstData.map(item => {
         const secondItem = secondData && secondData.find(secondItem => secondItem.id === item.id)
         if (secondItem) {
           return {
             ...item,
             highest: secondItem.score
           };
         } else {
           return {
             ...item,
             highest: ''
           };
         }
       }); 
       console.log("result",result);
    
    Login or Signup to reply.
  2. You can use reduce() to build up a lookup object (or alternatively a Map) which maps a user ID to a score and then use map() over the second array to use the user ID as a key to lookup the score for the user user currently iterating over. If the lookup is successful, return a new object with the property highest set to the lookup result. If not, just return a copy of the original object (of course you could also set a default value or whatever makes sense in your case).

    The solution will be O(n) in terms of time complexity.

    const firstArray = [
      {
        name: "sachin",
        id: 1,
      },
      {
        name: "dravid",
        id: 2,
      },
      {
        name: "ganguly",
        id: 3,
      },
    ];
    
    const secondArray = [
      {
        score: 186,
        id: 1,
      },
      {
        score: 145,
        id: 2,
      },
      {
        score: 183,
        id: 3,
      },
    ];
    
    const scoreById = secondArray.reduce(
      (acc, cur) => ((acc[cur.id] = cur.score), acc),
      {}
    );
    const result = firstArray.map((x) =>
      scoreById[x.id] ? { ...x, highest: scoreById[x.id] } : { ...x }
    );
    
    console.log(JSON.stringify(result, null, 4));
    /* Stackoverflow: show only console */
    .as-console-wrapper {
      max-height: 100% !important;
      top: 0;
    }

    Alternatively instead of building up a lookup table you could also use find() and do a linear search in the array, which brings the overall time complexity to O(n²) but in reality depending on how many elements you expect this might be faster. For general purposes the difference probably won’t matter much and if you need the performance measure, compare and then make a conscious decision.

    Login or Signup to reply.
  3. There are a lot of ways to do this. This is what I would do in my case:

    // Function to find the highest score for given id
    const findHighestScore = (id) => {
      const secondItem = secondData.find(item => item.id === id);
      return secondItem ? secondItem.score : ''; 
    };
    
    // Map through the first array and add the highest score if id matches
    const result = firstData.map(item => ({
      ...item,
      highest: findHighestScore(item.id)
    }));
    
    console.log("result", result);
    

    Do try this and see how it goes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search