I have an array which looks like:
const arr = [1,2,3,4,5,6]
I want to convert this array to look something like
const arr2 = [ {x: 1, y, 2}, {x:3, y:4}, {x:5, y:6}]
I have tried something like this:
let res: any = [];
const arr = [1,2,3,4,5,6]
for (let i = 0; i < arr.length / 2; i++) {
let next = 0
res.push({x : arr[i + next], y : arr[i+1+next]})
next += 2;
}
But this doesnt give me the correct results.
const arr = [1, 2, 3, 4, 5, 6, 7]
var result = [];
for (var i = 0; i < arr.length; i += 2) {
result.push({
x: arr[i],
y: i + 1 < arr.length ? arr[i + 1] : undefined
})
}
console.log(result)
convertToPoints = (arr) => {
let arr2 = [];
// if arr does not contain an even amount of elements, return false
if (arr.length % 2 !== 0) {
return false;
}
for (let i = 0; i < arr.length - 1; i += 2) {
arr2.push({ x: arr[i], y: arr[i+1] });
}
return arr2;
}
You could get pairs of sliced arrays and create new objects with short hand properties.
const
array = [1, 2, 3, 4, 5, 6],
result = [];
let i = 0;
while (i < array.length) {
const [x, y] = array.slice(i, i += 2);
result.push({ x, y });
}
console.log(result);
A better approach with a simple loop.
const
array = [1, 2, 3, 4, 5, 6],
result = [];
for (let i = 0; i < array.length; i += 2) {
result.push({ x: array[i], y: array[1 + 1] });
}
console.log(result);