Input arrays :
var arr1 = [{EmpID:'1',Name:'PB',EmpCode:'10001'},{EmpID:'2',Name:'SS',EmpCode:'10002'}];
var arr2 = [{EmpID:'1',Address:'GGN'},{EmpID:'2',Address:'SP-GGN'}];
Expected Output :
[{EmpID:'1',Name:'PB',EmpCode:'10001',Address:'GGN'},{EmpID:'2',Name:'SS',EmpCode:'10002',Address:'SP-GGN'}];
I tried below logic
function fun(){
var arr1 = [{EmpID:'1',Name:'PB',EmpCode:'10001'},{EmpID:'2',Name:'SS',EmpCode:'10002'}];
var arr2 = [{EmpID:'1',Address:'GGN'},{EmpID:'2',Address:'SP-GGN'}];
var arr3= [];
for(var k=0; k < arr1.length; k++){
arr3.push(arr1[k]);
}
for(var k=0; k < arr2.length; k++){
arr3.push(arr2[k]);
}
console.log(arr3);
var arr4 = [...arr1, ...arr2];
console.log(arr4);
}
fun();
output result :
[{"EmpID": "2", "Name": "SS", "EmpCode": "10002"},{EmpID: '2', Name: 'SS', EmpCode: '10002'},{EmpID: '1', Address: 'GGN'},{EmpID: '2', Address: 'SP-GGN'}]
We can’t use array.filter()
, .find()
, nested loop etc.., only customize logic is allowed.
Expected Output :
[{EmpID:'1',Name:'PB',EmpCode:'10001',Address:'GGN'},{EmpID:'2',Name:'SS',EmpCode:'10002',Address:'SP-GGN'}];
5
Answers
To achieve what you want, you can use a nested for loop to match the EmpID from both arrays. I think that should work:
here my code
I have updated your code, there are some minor mistakes in what you are doing, you need to put a second loop in the first loop, so that you can match the
EmpID
and then you in the objectAddress
needs to be added according to theEmpID
and then you need to push the object in thearr3
, as you can see in the code below.You could use two loops behind with an object for grouping instead nested loops.
This approach takes an object for grouping objects by
EmpID
and an array for the result set.If you are allowed to use
Object.values
, you could omitresult
and return only the values ofreferences
.