Cal*_*Oki 3 javascript arrays algorithm
给定以下数组
let array = [[1, 2], [1, 2], [3, 4], [5, 6], [2, 1]]
Run Code Online (Sandbox Code Playgroud)
I want to return the number of distinct arrays in this set. So the example above should return 3. How do I achieve this? I tried the code below, but it does not give the right answer
let distinct = 0
for (let i = 0; i < array.length; i++) {
for (let j = i + 1; j < array.length - i; j++) {
let difference = ingredients[i].filter(x => !array[j].includes(x))
if (difference.length > 0) {
distinct += 1;
}
}
}
return distinct;
Run Code Online (Sandbox Code Playgroud)
Ori*_*ori 10
Use Array.map() to convert each sub-array into a string (I've used String() as suggested by @trincot), create a Set from the array to remove duplicates, and get the size of the Set:
const array = [[1, 2], [1, 2], [3, 4], [5, 6]]
const distinct = new Set(array.map(String))
console.log(distinct.size)Run Code Online (Sandbox Code Playgroud)
Sort each sub item, and then convert to string:
const array = [[2, 1], [1, 2], [3, 4], [5, 6]]
const distinct = new Set(array.map(o => String(o.sort())))
console.log(distinct.size)Run Code Online (Sandbox Code Playgroud)