I have an array which i need to compare it's values - and if there are duplication - i want to store them in array, for example :
obj1 = [{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"},
{"manager_id":2,"name":"kenny"},
{"manager_id":4,"name":"stan"}]
obj2 = [{"employees_id":1,"name":"dan"},
{"employees_id":1,"name":"ben"},{"employees_id":1,"name":"sarah"},
{"employees_id":2,"name":"kelly"}]
If "manger_id" === "employees_id - then the result would be :
// {1:[{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"},
{"employees_id":1,"name":"dan"}, {"employees_id":1,"name":"ben"},
{"employees_id":1,"name":"sarah"}]};
I've tried :
var obj1 = [{
"manager_id": 1,
"name": "john"
}, {
"manager_id": 1,
"name": "kile"
}, {
"manager_id": 2,
"name": "kenny"
}, {
"manager_id": 4,
"name": "stan"
}];
var obj2 = [{
"employees_id": 1,
"name": "dan"
}, {
"employees_id": 1,
"name": "ben"
}, {
"employees_id": 1,
"name": "sarah"
}, {
"employees_id": 2,
"name": "kelly"
}];
var res = obj1.concat(obj2).reduce(function(r, o) {
r[o.manager_id] = r[o.employees_id] || [];
r[o.manager_id].push(o);
return r;
}, {});
console.log(res);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
As you can the results of the "manager_id" aren't added - only one - when there should be more
if manager_id === employees_id // should output in the first key
{1:[{"manager_id":1,"name":"john"},{"manager_id":1,"name":"kile"},
{"employees_id":1,"name":"dan"}, {"employees_id":1,"name":"ben"},
{"employees_id":1,"name":"sarah"}]};
As you can see there are several common id's
r[o.manager_id] = r[o.employees_id] || [];
in this statement if a manager didn't have an employee_id the array was being reset for that id.
One way doing it right is this:
var res = obj1.concat(obj2).reduce(function(r, o) {
var id;
if(o.hasOwnProperty('manager_id')) {
id = o['manager_id'];
}
else {
id = o['employees_id'];
}
r[id] = r[id] || [];
r[id].push(o);
return r;
}, {});