Skip to content

J030 Array Play

A straightforward task working with arrays in ES (ECMAScript).

Create an empty app.js and:

Array Basics

  • Create an array with values 1, 5, 7, 15, 2, 6, 4.
  • Print the array to the console.
  • Add a value to the array using the push method.
  • Print the array to the console.
  • Remove a value from the array using the pop method and store it in a new variable.
  • Print the array and the new variable to the console.
  • Print the array using forEach.
  • Sort the array using the sort method.
  • Print the array to the console.
    • Note that sorting is based on strings by default.
    • Extra: Try calling sort() with a reference to a compare method.
Solution
"use strict";

// Array Basics
let numbers = [1, 5, 7, 15, 2, 6, 4];
console.log(numbers);

numbers.push(5);
console.log(numbers);

let removedValue = numbers.pop();
console.log(numbers, `removedValue=${removedValue}`);

numbers.forEach(function(value,index,array){
    console.log(value);
});

numbers.sort();
console.log(numbers); // Note: This sort will not work correctly because it's based on strings.

// Sorting with a compare method (could be an arrow function)
numbers.sort(function(n1, n2){
    if(n1 < n2){
        return -1;
    } else if(n1 > n2){
        return 1;
    }
    return 0;
});
console.log(numbers);

Executing this script will print the array as described, showcasing the behaviors of the different array methods used.