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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With