Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicate objects in object array while keeping unique string values

Please bear with me, I'm a novice javascript developer with a sorting problem that I can't wrap my head around.

I'm retrieving an array of objects (JSON response) by an api like this:

var arr = [
    {
        "year": "2011",
        "activity": "bowling"
    },
    {
        "year": "2009",
        "activity": "shopping",
    },
    {
        "year": "2011",
        "activity": "cooking"
    },
    {
        "year": "2006",
        "activity": "singing"
    }
]

I have a function that removes all of the duplicate years (as intended), but I wish to take the 'activity' value of the duplicate object and add it to the activity value of that same year is left after removing duplicates

My function that removes the duplicate year is as follows

var new_arr = new_arr.reduce((unique, o) => {
  if(!unique.some(obj => obj.year === o.year)) {
    unique.push(o);
  }
  return unique;
},[]);

which leaves me with this

var arr = [
    {
        "year": "2011",
        "activity": "bowling"
    },
    {
        "year": "2009",
        "activity": "shopping",
    },
    {
        "year": "2006",
        "activity": "singing"
    }
]

What I wish to accomplish:

var arr = [
    {
        "year": "2011",
        "activity": "bowling, cooking"
    },
    {
        "year": "2009",
        "activity": "shopping",
    },
    {
        "year": "2006",
        "activity": "singing"
    }
]

JSFiddle: https://jsfiddle.net/4s1uaex0/2/

I feel like I'm almost there, but I don't know where to start from here. Can anyone point me into the right direction with a guide or example? Help would be greatly appreciated! Thank you

like image 575
kubmin Avatar asked Sep 04 '26 15:09

kubmin


1 Answers

you can simply use for loop

    var mem = {};
    for(var i = 0; i < arr.length; i++) {
        var currentItem = arr[i];
        var year = currentItem['year'];
        var activity =  currentItem['activity'];
        if(!mem.hasOwnProperty(year)) {
            mem[year] = { 'year' : year, "activity": []};
        }
        mem[year]['activity'].push(activity);
    }

    var final = Object.values(mem);
like image 60
Saurabh Yadav Avatar answered Sep 07 '26 06:09

Saurabh Yadav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!