VMware Cloud Community
lurims
Enthusiast
Enthusiast
Jump to solution

Having hard time in the java script array element compare

I have an array with duplicate items.  It is something like this.

Emp#, UserName

516, John

6474, Krish

34, Peter

516, Kesi

869, Kala

516, Yash

34, Henry

516, Oswal

I want to print the usernames those share the same Emp ID something like this.

John, Kesi, Yash and Oswal are sharing the same Employee ID, 516

Peter and Henry are sharing the same Employee ID, 34

I have tried several ways, but was not successful.  Any idea?

Tags (1)
Reply
0 Kudos
1 Solution

Accepted Solutions
iiliev
VMware Employee
VMware Employee
Jump to solution

Something like the following?

It assumes that the input data is represented as an array, and every element of it is another array with exactly 2 elements (employee ID and user name), both of which are strings. The same code can be easily adapted to work with different format of the input data, if necessary.

// Emp#, UserName

var data = [

  [ "516", "John" ],

  [ "6474", "Krish" ],

  [ "34", "Peter" ],

  [ "516", "Kesi" ],

  [ "869", "Kala" ],

  [ "516", "Yash" ],

  [ "34", "Henry" ],

  [ "516", "Oswal" ]

]

var groupByEmpId = function(array) {

  return array.reduce(function(acc, v) {

    if (acc[v[0]] == null) acc[v[0]] = [v[0]]

    acc[v[0]].push(v[1]);

    return acc;

  }, {});

};

for each (var group in groupByEmpId(data)) {

  var id = group.shift();

  System.log("Employee ID " + id + " is shared by " + group);

}

---------------------------------------------------------------------------------------------------------

Was it helpful? Let us know by completing this short survey here.

View solution in original post

1 Reply
iiliev
VMware Employee
VMware Employee
Jump to solution

Something like the following?

It assumes that the input data is represented as an array, and every element of it is another array with exactly 2 elements (employee ID and user name), both of which are strings. The same code can be easily adapted to work with different format of the input data, if necessary.

// Emp#, UserName

var data = [

  [ "516", "John" ],

  [ "6474", "Krish" ],

  [ "34", "Peter" ],

  [ "516", "Kesi" ],

  [ "869", "Kala" ],

  [ "516", "Yash" ],

  [ "34", "Henry" ],

  [ "516", "Oswal" ]

]

var groupByEmpId = function(array) {

  return array.reduce(function(acc, v) {

    if (acc[v[0]] == null) acc[v[0]] = [v[0]]

    acc[v[0]].push(v[1]);

    return acc;

  }, {});

};

for each (var group in groupByEmpId(data)) {

  var id = group.shift();

  System.log("Employee ID " + id + " is shared by " + group);

}

---------------------------------------------------------------------------------------------------------

Was it helpful? Let us know by completing this short survey here.