I have an array like so [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7]
How can I turn it into a 2-dimensional array that's based on matching numbers before the decimal?
ex.[[1.2, 1.3, 1.4], [2.2, 2.3], [3.0], [4.3, 4.4, 4.5, 4.6, 4.7]]
I have an array like so [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7]
How can I turn it into a 2-dimensional array that's based on matching numbers before the decimal?
ex.[[1.2, 1.3, 1.4], [2.2, 2.3], [3.0], [4.3, 4.4, 4.5, 4.6, 4.7]]
You can use Array.reduce to do this, building an array using indexes based on the integer portion of each value:
arr = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];
let res = arr.reduce((c, v) => {
i = Math.trunc(v) - 1;
c[i] = c[i] || [];
c[i].push(v);
return c;
}, []);
console.log(res);
If you could have values starting at 0, or gaps in the values, you can use a similar piece of code and then use Object.values() to just extract the filled in arrays:
arr = [0.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 6.6, 8.7];
res = arr.reduce((c, v) => {
i = Math.trunc(v);
c[i] = c[i] || [];
c[i].push(v);
return c;
}, []);
res = Object.values(res)
console.log(res);
Assuming you want empty arrays in between, you can use reduce() like this:
const numbers = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];
const grouped = numbers.reduce(
(result, number) => {
result[Math.trunc(number)].push(number);
return result;
},
Array(Math.trunc(Math.max(...numbers)) + 1).fill().map(() => [])
);
Result:
[
[],
[1.2,1.3,1.4],
[2.2,2.3],
[3],
[4.3,4.4,4.5,4.6,4.7]
]
Since it's always sorted, you can use this imperative approach:
const arr = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];
let curr = -Infinity;
let currArr = null;
const res = [];
for (let n of arr) {
if (Math.trunc(n) > curr) {
res.push(currArr = [curr = n]);
} else {
currArr.push(n);
}
}
console.log(res);
It just tracks the latest number, and its current sub-array. If the next integer is greater than the current number, it creates a new array, otherwise it pushes into the current sub-array.
Some may not like using the result of an assignment as a value. If not, it can easily be reworked with a couple extra lines of code.
use sort, then traverse using forEach and group based on Math.floor value.
const split = (data) => {
const output = [];
let temp = [];
data
.sort((a, b) => a - b)
.forEach((num) => {
const [first] = temp;
if (first && Math.floor(num) > Math.floor(first)) {
output.push([...temp]);
temp = [];
}
temp.push(num);
});
if (temp.length > 0) {
output.push([...temp]);
}
return output;
};
const data = [1.2, 1.3, 1.4, 2.2, 2.3, 3.0, 4.3, 4.4, 4.5, 4.6, 4.7];
console.log(split(data));