2

I'm trying to figure out an efficient method to sort a multidimensional array based on how many values of another array exist.

Given the following array: [1,2,3,4,5,6,7,8,9,10]

I am trying to sort another array of arrays based on how many of those values are included.

[
  [1,3,5,7,9,22],
  [1,200,300,400,500,600],
  [1,2,3,4,5,6]
]

So the code I'm trying to get to would return:

[
  [1,2,3,4,5,6],
  [1,3,5,7,9,22],
  [1,200,300,400,500,600]
]

I think what I'm doing is very inefficient and could be written better or more succinctly with a method I'm not aware of?

https://jsfiddle.net/gb3fsLdv/

const compareNums = [1,2,3,4,5,6,7,8,9,10];
let ourData = [
  [1,2,3,100,200,300],
  [100,200,300,400,500,600],
  [1,2,3,5,6,9]
];

function sortArr(compare, data){
  let indexMatches = [];
  data.map(arr => {
    let count = 0;
    compare.map(num => {
      if(arr.includes(num)){ 
        count++ 
        }
    })
    indexMatches.push(count);
  })
  // So now I have indexMatches with a count of how many hits each array has in the correct index order as the original data
  // And I can use data to sort them based on these values...
  // Little stuck how to relate the two so the same sorting happens to both arrays
}

sortArr(compareNums, ourData);

1 Answer 1

2

First convert the given array to set. And then use filter() to get the count of elements included in other array

const data = [
  [1,3,5,7,9,22],
  [1,200,300,400,500,600],
  [1,2,3,4,5,6]
]

let arr = [1,2,3,4,5,6,7,8,9,10];

function getCount(arr, set){
  return arr.filter(x => set.has(x)).length
}
function sortOnCount(data, arr){
  let set = new Set(arr);
  return data.slice(0).sort((a, b) => getCount(b, set) - getCount(a, set))
}

console.log(sortOnCount(data, arr))

Sign up to request clarification or add additional context in comments.

1 Comment

Looks extremely effective and easily maintainable. Thanks. Selecting correct answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.