DEV Community

Cover image for JavaScript Katas: Split a number array into odd and even numbers
miku86
miku86

Posted on

JavaScript Katas: Split a number array into odd and even numbers

Intro 🌐

Today, I start a new series about code katas.

I will take interesting katas of all levels and explain how to solve them.

Problem solving is an important skill, for your career and your life in general.

You'd better learn to solve problems!


Source

I take the ideas for the katas from different sources and re-write them.

Today's source: Codewars


Understanding the Exercise ❗

First, we need to understand the exercise!

This is a crucial part of (software) engineering.

Go over the exercise explanation again until you understand it 100%.

Do NOT try to save time here.

My method to do this:

  1. Input: What do I put in?
  2. Output: What do I want to get out?

Today's exercise

Write a function splitOddAndEven, that accepts one parameter: numbers, an array of positive numbers.

The function should return an object with two arrays in it, one for all odd numbers and one for all even numbers.


Input: an array of numbers.

Output: an object with two arrays of numbers, one for the odd ones, one for the even ones.


Thinking about the Solution 💭

I think I understand the exercise (= what I put into the function and what I want to get out of it).

Now, I need the specific steps to get from input to output.

I try to do this in small baby steps.

  • loop over the input array
  • if number is odd, save it in a variable odd
  • if number is even, save it in a variable even
  • return odd and even in an object

Example:

  • Input: [1, 2, 3]
  • Round 1: odd = [1] // first number in array is 1, which is odd, therefore goes into odd array
  • Round 2: even = [2] // second number in array is 2, which is even, therefore goes into even array
  • Round 3: odd = [1, 3] // third number in array is 3, which is odd, therefore goes into odd array, too
  • Output: { odd: [1, 3], even: [2] } // put odd array and even array in an object

Implementation (for loop) ⛑

function splitOddAndEven(numbers) {
  let odd = [];
  let even = [];

  for (let i = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 === 0) {
      // number is even
      even.push(numbers[i]);
    } else {
      // number is not even (=odd)
      odd.push(numbers[i]);
    }
  }

  // create an object with the odd and even array in it
  const returnObject = {
    odd,
    even,
  };

  return returnObject;
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(splitOddAndEven([1, 2, 3]));
// { odd: [ 1, 3 ], even: [ 2 ] }

console.log(splitOddAndEven([0, 3, 5]));
// { odd: [ 3, 5 ], even: [ 0 ] }
Enter fullscreen mode Exit fullscreen mode

Implementation (for of-loop) ⛑

function splitOddAndEven(numbers) {
  let odd = [];
  let even = [];

  for (const number of numbers) {
    if (number % 2 === 0) {
      // number is even
      even.push(number);
    } else {
      // number is not even (=odd)
      odd.push(number);
    }
  }

  // create an object with the odd and even array in it
  const returnObject = {
    odd,
    even,
  };

  return returnObject;
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(splitOddAndEven([1, 2, 3]));
// { odd: [ 1, 3 ], even: [ 2 ] }

console.log(splitOddAndEven([0, 3, 5]));
// { odd: [ 3, 5 ], even: [ 0 ] }
Enter fullscreen mode Exit fullscreen mode

Implementation (Functional) ⛑

function splitOddAndEven(numbers) {
  // filter out the odd numbers
  const odd = numbers.filter((number) => number % 2 === 1);

  // filter out the even numbers
  const even = numbers.filter((number) => number % 2 === 0);

  // create an object with the odd and even array in it
  const returnObject = {
    odd,
    even,
  };

  return returnObject;
}
Enter fullscreen mode Exit fullscreen mode

Result

console.log(splitOddAndEven([1, 2, 3]));
// { odd: [ 1, 3 ], even: [ 2 ] }

console.log(splitOddAndEven([0, 3, 5]));
// { odd: [ 3, 5 ], even: [ 0 ] }
Enter fullscreen mode Exit fullscreen mode

Playground ⚽

You can play around with the code here


Next Part ➡️

Great work, mate!

Next time, we'll solve the next kata. Stay tuned!

If I should solve a specific kata, shoot me a message here.

I would love to get in touch with you!


Further Reading 📖


Questions ❔

  • Do you like to solve katas?
  • Which implementation do you like more? Why?
  • Any alternative solution?

Top comments (11)

Collapse
 
256hz profile image
Abe Dolinger


const splitNumbers = numbers => {
    const oddsAndEvens = { odds: [], evens: [] };

    numbers.forEach(number => {
        oddsAndEvens[number % 2 === 0 ? 'evens' : 'odds']
            .push(number);
    };

    return oddsAndEvens;
};

Collapse
 
miku86 profile image
miku86

Hi Abe,

nice solution, thanks!

Collapse
 
256hz profile image
Abe Dolinger

All credit to this post! codereview.stackexchange.com/a/162... Been using this at work and loving it.

Collapse
 
pentacular profile image
pentacular • Edited

The problem with katas is that they ignore the 'why' of the problem.

Since we don't know why we're doing this, let's delegate that problem to the caller as much as possible.

This is really a classification problem.

const splitNumber = (numbers, emitEven, emitOdd) =>
  numbers.forEach(n => (n % 2 ? emitOdd : emitEven)(number));

Now we can defer the arrangement of the classified numbers to someone else.

If they want to store them in arrays, then they can do that.

const even = [];
const odd = [];
splitNumber(numbers, n => even.push(n), n => odd.push(n));

But that's their problem.

Collapse
 
d4rthv4d3r profile image
Julián Chamalé

Nice analysis

Collapse
 
miku86 profile image
miku86

Hi,

thanks for your insights,
interesting question to think about!

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Or a simple reduce for the functional way

numbers.reduce((acc,val)=>{
return (val%2===1 ? {...acc,odd:[...acc.odd,val]}:{...acc,even:[...acc.even,val]});
},{odd:[],even:[]})

Collapse
 
monicamakes profile image
Monica

I was just going to comment, that this would also be done with reduce (my favorite)

Collapse
 
sqlrob profile image
Robert Myers

Yeah, I would've gone with the reduce too, since that's only one iteration over the array, not two. Not sure I'd use spread though, wouldn't that kill the gain?

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Probably it would, so just mutate the acc and return it, I think even after all the solutions, I think the simple for loop performs the best.

Collapse
 
miku86 profile image
miku86

Hey there,

thanks for your solution!
Nice opportunity for people who want to step up their reduce-skills.