Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

255
Views
How to transform an array of [x: x1, y: y1] to an array of numbers where the numbers are stored like [x1, y1, x2, y2....] in javascript?

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!