Skip to Main Content

Sort Array By Parity

Problem URL:Sort Array By Parity

My Solution

JavaScript

/**
 * @param {number[]} A
 * @return {number[]}
 */

const sortArrayByParity = (A) => {
  let sorted_A = [];
  A.forEach(function (n) {
    if (n % 2 === 0) sorted_A.unshift(n); // if even, add to beginning of array
    else sorted_A.push(n); // if odd, add to end of array
  });

  return sorted_A;
};

Let's Connect

Twitter GitHub LinkedIn