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.
CodePudding user response:
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);
CodePudding user response:
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)
CodePudding user response:
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;
}
CodePudding user response:
You can do this with reduce
arr.reduce((acc,curr,index) => {
if(index % 2) {
acc[acc.length-1].y = curr
return acc
}
return acc.concat({x:curr})
}, [])
CodePudding user response:
You can join the numbers and then group the coordinates by using a Regexp along with the replacer function from the function String.prototype.replace
.
const arr = [1,2,3,4,5,6];
const result = [];
arr.join("")
.replace(/([0-9]{2})/g, coordinates => {
const [x,y] = coordinates.split("");
result.push({x,y});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }