JSFiddle - React, Tailwind, and code Playground

by rexonms

JavaScript

student_course_pairs_1 = [
  ["58", "Software Design"],
  ["58", "Linear Algebra"],
  ["94", "Art History"],
  ["94", "Operating Systems"],
  ["17", "Software Design"],
  ["58", "Mechanics"],
  ["58", "Economics"],
  ["17", "Linear Algebra"],
  ["17", "Political Science"],
  ["94", "Economics"],
  ["25", "Economics"],
]

const findPairs = (arr) => {
	let toReturn = {};
  let mapping = {};
  arr.map((i) => { // ["58", "Soft..."]
   		const key = i[0];
      const value = mapping[key] ? [...mapping[key], i[1]] : [i[1]] ;
    	mapping[key] = value;
  	})
  // toReturn = { 58: ["Software ...", "linear"] }
  // console.log('mapping', mapping);
  Object.keys(mapping).map((i, index) => { // ["58", "Soft..."]
   		// if the value of the key is here add it
      // 17 software
      const studentId = i;
      const courses = mapping[i];    
       arr.map(i => {
        const secondStudentId = i[0];
        const secondCourse = i[1];
        const reverseKey = [secondStudentId, studentId]
        if (studentId !== secondStudentId &&
        	courses.find(item => item === secondCourse) &&
         	toReturn[reverseKey] === undefined
          ) {
          const studentIds = [studentId, secondStudentId];
          const matchedCourses = toReturn[studentIds] ?
            [...toReturn[studentIds],secondCourse] :
            [secondCourse]; 
          toReturn[studentIds] = matchedCourses;
        }
      })
  	})
  return toReturn;
}
console.log(findPairs(student_course_pairs_1));