Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare array of array elements between each other in JavaScript

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading