Monday, February 10, 2020

Javascript program - Split array of numbers into two (numbers less than 12 and numbers greater than 12)

Javascript - Split array of numbers into two...

This JS code will return (lessThan_12) for numbers less than 12 from the given array of numbers and numbers greater than 12 as (greaterThan_12).


// Define the array...
const array_of_numbers = [10, 2, 34, 11, 5, 9, 100, 23, 29, 56, 3, 4, 50, 12, 7, 8];

// Define empty arrays to hold the two expected arrays...
let greaterThan_12 = [];
let lessThan_12 = [];

// Using 'for each' loop to loop over the array's element and push relevant to empty array
array_of_numbers.forEach(runFunc);

function runFunc(x) {
 if (x > 12){
  greaterThan_12.push(x);
 } else if (x < 12) {
  lessThan_12.push(x);
 }
}

// Lets see what is in each array...?
console.log(greaterThan_12);
console.log(lessThan_12);



The comment has explained everything in the script :). The only difficult part that may require some explanation is the forEach() loop, which takes a function 'runFunc()' that performs the magic.


Note: if you want 12 to be included in either arrays use >= "greater than or equal to" or <= "less than or equal to". If you use both, only the first case will be applied.

// Define the array...
const array_of_numbers = [10, 2, 34, 11, 5, 9, 100, 23, 29, 56, 3, 4, 50, 12, 7, 8];

// Define empty arrays to hold the two expected arrays...
let greaterThan_12 = [];
let lessThan_12 = [];

// Using 'for each' loop to loop over the array's element and push relevant to empty array
array_of_numbers.forEach(runFunc);

function runFunc(x) {
 if (x >= 12){
  greaterThan_12.push(x);
 } else if (x <= 12) {
  lessThan_12.push(x);
 }
}

// Lets see what is in each array...?
console.log(greaterThan_12);
console.log(lessThan_12);


No comments:

Post a Comment