JSFiddle - React, Tailwind, and code Playground
HTML
<div id ='result'></div>
JavaScript
var carArray = [1,8,4,6,5,7]; // ["1,8", "4,6,8", "8,9", "6,9"];
//1) create single array
var arr = carArray .join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, res;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
res = el;
}
});
if(res){
//there was an element more than once, maxOccuring contains that element
setResult('Most occuring: ' + res + ' (' + max + ' times)');
}
else{
//3 & 4)
var cmpArr = ['6','7','4','1','2','8','9','5'];
//sort based on the index of compare array:
res = function(){ for(var i= 0 ; i < cmpArr.length; i++){ if(arr.indexOf(cmpArr[i]) !== -1)return cmpArr[i];}}();
setResult('Element by unique sort order: ' + res);
}
//variable res contains the found element in both cases
//below is only for test display purposes
function setResult(res){
console.log(res);
$('#result').text(res);
}