Help

Save the date! Join us on October 16 for our Product Ops launch event. Register here.

Merge duplicates inside the array

1218 1
cancel
Showing results for 
Search instead for 
Did you mean: 
Marc_Justin_Rai
6 - Interface Innovator
6 - Interface Innovator

Hi, Is it possible find the same rid from array to array2 then push the wordspin values inside the array variable but i can’t use .find as it result to error.

let id1 = "recQoA4zwa0xZQVGL";
let id2 = "reckssVy1WsRtWPQs";
let id3 = "recSu7GQqd85dC5go";

let array2 = [
  {rid : id1, wordspin : "test1"},
  {rid : id2, wordspin : "test2"},
  {rid : id3, wordspin : "test3"},
  {rid : id1, wordspin : "test11"},
  {rid : id2, wordspin : "test22"},
  {rid : id3, wordspin : "test33"},
  {rid : id1, wordspin : "test111"},
  {rid : id2, wordspin : "test222"},
  {rid : id3, wordspin : "test333"}
]
let result = array2.forEach(function rid(r) {
    return function (o) {
        var ref = r.find(p => o.rid === p.rid);
        if (!ref) {
            r.push(o);
            return;
        }
        Object
            .keys(o)
            .filter(k => Array.isArray(o[k]))
            .forEach(k => o[k].forEach(rid(ref[k] = ref[k] || [])));
    };
});

I want my result to look like this

[
  {rid:id1, 
  wordspin : "test1",
  wordspin2 : "test11",
  wordspin3 : "test111"
  }
  {rid:id2, 
  wordspin : "test2",
  wordspin2 : "test22",
  wordspin3 : "test222"
  }
  {rid:id3, 
  wordspin : "test3",
  wordspin2 : "test33",
  wordspin3 : "test333"
  }
]
1 Reply 1

Hi,

Yesterday I wrote a script to transpose vertical table to horizontal and stuck into object grouping task, which is similar to yours.
After your post I understood that I went wrong way, and how to solve my puzzle ))
So let’s help with yours.
besides grouping, you have other challenge - add new object properties according to those already existing. If wordspin2 property already exists, wordspin3 should be added and so on…
I belieive it has other easier solutions, maybe with spread+destruct, but I would use map array and transform to object.

const wsAdd=x=>x.map((val,ix)=>['wordspin'+ix,val])
const wsObj=x=>Object.fromEntries(wsAdd(x))

group objects by Id is a standard task which have a lot of ways to do.
I took this reducer from net and changed a bit, to add just ‘wordspin’ properties and to get an ‘array of arrays’ on exit
const group=(arr,key,val)=>arr.reduce((res,el)=>((res[el[key]]=[...(res[el[key]]||[]),el[val]]),res),[])

now we need to connect these two ‘data processors’

const grouped = group(array2,'rid','wordspin')
const entries=(Object.entries(grouped));
const result=entries.flatMap(key=>({'rid':key[0],...wsObj(key[1])}))
output.inspect(result)

and here we go !
(if you need to correct numbers near ‘wordspin’ (start from 1 etc) - edit wsAdd function)

image