i am newly learn javascript, now i am having a serios compare in here.
In one nested array how to compare each array elements are same to other array elemnts or not?
if array elements are same then will display rest of elemnts for both array in one array.
suppose the codes like this:
const arr= [[100110, 556781, 'student', 'single' , 20, 'jacci'],
[100210, 667881 , 'employee', 'double' , 25, 'rock'],
[100310, 778981 ,'teacher', 'triple' , 45, 'poul'],
[100220, 667891 , 'employee', 'single' , 30, 'jack'],
[100320, 778991 ,'teacher', 'double' , 40, 'rose'],
[100120, 556791, 'student', 'double' , 35, 'laila']];
now i want to compare each array frist 2 index are same, if same then the array will be like:
arry = [[1001, 'student', 'single' , 20, 'jacci','double' , 35, 'laila'],
[1002, 'employee', 'double' , 25, 'rock','single' , 30, 'jack'],
[1003, 'teacher', 'triple' , 45, 'poul', 'double' , 40, 'rose']]
how can i get the array like this in javascript.
anyone can help me to do the function for it.
Thanks for your trying in advance!
>Solution :
You can do something like this
const arr=[[1001,"student","single",20,"jacci"],[1002,"employee","double",25,"rock"],[1003,"teacher","triple",45,"poul"],[1002,"employee","single",30,"jack"],[1003,"teacher","double",40,"rose"],[1001,"student","double",35,"laila"],];
const group = (data) => {
const map = {};
data.forEach(([id, type, ...rest]) => {
const key = `${id}|${type}`;
if (!map[key]) {
map[key] = [id, type];
}
map[key].push(...rest);
});
return Object.values(map);
};
console.log(group(arr))