-2

I have an array which contains many objects(all this data will come via ajax call, for example lets say there are only 3 records).

data : [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];

Is there any way to loop through entire array and find objects with same id and concatenate their names and filter the array to be like this

data : [{name : "a,c",id : "100"},{name : "b",id:"101"}]

Thanks

tekas
  • 21
  • 1
  • 2
  • 4
  • 2
    To answer your question, yes it is possible – Suresh Atta May 12 '17 at 10:28
  • 3
    Yes there are many ways. Look through Array functions, I suggest [reduce](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce?v=example) – Daniel Cooke May 12 '17 at 10:28
  • 1
    Possible duplicate of [What is the most efficient method to groupby on a javascript array of objects?](http://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array-of-objects) – cнŝdk May 12 '17 at 10:34

2 Answers2

1

You can use forEach() loop and check if id exists and concat name to that value.

var data = [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];
var result = []

data.forEach(function(e) {
  //Check if property with current object id exists in object provided as thisArg param and if it doesn't exists set its value to current object and push it to result array
  if(!this[e.id]) this[e.id] = e, result.push(this[e.id])
  // if it does exists then concat name of current object to name of existing one that had the same id
  else this[e.id].name += ',' + e.name
}, Object.create(null))

console.log(result)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
  • Thanks Nenad.Much appreciated. – tekas May 12 '17 at 10:34
  • I recommend explaining how it works. Code is good, but explanation would **really** help. In particular, the tricky bit with using `this` and a blank object. (Side note: Beware naming conflicts with `Object.prototype`, I suggest using `Object.create(null)`, not `{}`; or if using ES2015+, use a `Map`.) – T.J. Crowder May 12 '17 at 10:34
0

I suggest to use a hash table, which is used as a closure of the callback function. Then iterate over the objects and thest if the hash exists or not. If it exists, add the name to the name property of the object, otherwise create a new object with the actual data and push it to the result set.

Return the temporary array in Array#reduce.

var data = [{name : "a",id : "100"},{name : "b",id : "101"},{name : "c",id : "100"}];


data = data.reduce(function (hash) {
    return function (r, a) {
        if (hash[a.id]) {
            hash[a.id].name += ',' + a.name;
        } else {
            hash[a.id] = { name: a.name, id: a.id };
            r.push(hash[a.id]);
        }
        return r;
    };
}(Object.create(null)), []);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392