Not a question, just putting this out there if someone would need it. (caused me a lot of headache)
The script below can take a 2d array of any number number of 2nd-layer arrays as 'myArray' and create a single array of the most frequent element (regardless of type) in each column of the original 2d array.
myArray = myArray[0]
.map((_, col) => myArray.map((row) => row[col]))
.map((array) =>
array.reduce(
(a, b, i, arr) =>
arr.filter((v) => v === a).length >= arr.filter((v) => v === b).length
? a
: b,
null
)
);
What it does: The code below will take any two-dimensional array “myArray” and return a one-dimensional array with the mode of each column of the original 2-d array.
How it works: The input (2-d array) is transposed and the resulting array is searched for the most common element in each row. It is then reduced to then flattened (reduced) and re-transposed to a 1d array containing the most common elements of each column of the original array.
myArray = [
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 7],
[1, 3, 3, 6, 7],
[1, 5, 3, 4, 7],
[1, 6, 3, 4, 7],
[1, 7, 3, 8, 5],
];
myArray = myArray[0]
.map((_, col) => myArray.map((row) => row[col]))
.map((array) =>
array.reduce(
(a, b, i, arr) =>
arr.filter((v) => v === a).length >= arr.filter((v) => v === b).length ?
a :
b,
null
)
);
console.log(myArray);