Skip to main content

Arrays


  • const data = [1, 2, 3] is an array containing 3 numbers.
  • array.length returns the number of elements inside the array.
  • array.push(x) allows you to add the variable x to the end of the array.
  • array.push(x) returns the new length of the array (after the push has been made).
  • Arrays defined with const are not constants because you can change the elements inside of it. However, you cannot re-assign them to another value thus they will always be an array.

Defining an empty array


function getEmptyArray() {
const emptyArray = [];
return emptyArray;

}

// Sample usage - do not modify
console.log(getEmptyArray());

Returning Length of Array



function getNumberOfElements(elements) {
return elements.length;
}

// Sample usage - do not modify
console.log(getNumberOfElements(['a', 'b', 'c'])); // 3
console.log(getNumberOfElements([])); // 0

Adding to the array


You gotta push it and then return it.

function useCalculator(apps) {
apps.push("Calculator");
return apps;
}

Dynamic arrays


function useApp(apps, app) {
apps.push(app);
return apps;
}

// Sample usage - do not modify
console.log(useApp(["Clock", "Twitter"], "Firefox")); // ["Clock", "Twitter", "Firefox"]
console.log(useApp([], "Safari")); // ["Safari"]

Return first item in the array


function getFirstApp(apps) {
return apps[0];

}

// Sample usage - do not modify
console.log(getFirstApp(["Chrome", "Clock", "Twitter"])); // "Chrome"
console.log(getFirstApp(["Clock", "Contacts"])); // "Clock"

Return last item in the array


function getLastApp(apps) {
return apps[apps.length - 1];
}

// Sample usage - do not modify
console.log(getLastApp(["Chrome", "Clock", "Twitter"])); // "Twitter"
console.log(getLastApp(["Safari", "Contacts"])); // "Contacts"

Iterating over arrays with callback


  • .forEach(callback) iterates over every item in an array.
  • A callback is a function definition passed as an argument to another function.
  • Always start with a console.log() inside the .forEach() to visualize the shift from array to array item (you can skip that when you become used to it).
  • The .forEach() method will take your function definition and call it for every item of the array. Every time the callback is called, the first parameter will represent the corresponding array item.

Notes: Use the plural for the array and the singular for the item

Simple iteration


function loopThroughElements(elements) {
elements.forEach(function(element) {
console.log(element);
});
}

// Sample usage - do not modify
loopThroughElements(["Sam", "Charlie", "Alex"]); // should log every name to the console

Sum of elements in an array


function sumGrades(grades) {
let total = 0;
grades.forEach(function(grade) {
total = total + grade
});
return total;
}

// Sample usage - do not modify
console.log(sumGrades([15, 5, 10])); // 30
console.log(sumGrades([12, 10, 13, 19])); // 54

Adding only positive numbers of an array


function sumPositiveNumbers(numbers) {
let sum = 0; //outside of the foreach
numbers.forEach(function(number) {
if(number > 0){ // if the umber is greater than zero then it's positive
sum = sum + number //so then add those to the sum
}
});
return sum //return the value of sum after the numbers have been added.
}

Return sum of odd numbers


function sumOddNumbers(numbers) {
let oddTotal = 0
numbers.forEach(function(number) {
if(number % 2 === 1){
oddTotal = oddTotal + number
} else if(number %2 === -1) {
oddTotal = oddTotal + number
}
});
return oddTotal;
}

//or
function sumOddNumbers(numbers) {
let oddTotal= 0;
numbers.forEach(function(number) {
if (number % 2 !== 0) {
oddTotal = oddTotal + number;
}
});
return oddTotal;
}

// Sample usage - do not modify
console.log(sumOddNumbers([15, 5, 10])); // 20
console.log(sumOddNumbers([2, 3, 4, 5, 6])); // 8
console.log(sumOddNumbers([-2, -3, 4, 5, 6])); // 2


Return strings with variables from array


export function getDropdown(countries) {
let outputHTML = '<option value="">Please select</option>';
countries.forEach(function(country) {
outputHTML += '<option value="' + country.toLowerCase() + '">'+ country +'</option>'
});
return outputHTML;
}

//or

export function getDropdown(countries) {
let html = `<option value="">Please select</option>`;
countries.forEach(function(country) {
html += `<option value="${country.toLowerCase()}">${country}</option>`;
});
return html;
}

Nested arrays


This one was a little tricky. I started off trying to do an html += for every part, which put it all on the same line, but needed to have this format as one string.

export function renderTableRows(rows) {
let html = "";
rows.forEach(function(row) {
html += `<tr>
<td>${row[0]}</td>
<td>${row[1]}</td>
</tr>`
});

console.log(html)
return html;
}

Review


  • const data = [1, 2, 3] is an array containing 3 numbers.
  • array.length returns the number of elements inside the array.
  • array.push(x) allows you to add the variable x to the end of the array.
  • array.push(x) returns the new length of the array (after the push has been made).
  • Arrays defined with const are not constants because you can change the elements inside of it. However, you cannot re-assign them to another value thus they will always be an array.
  • .forEach(callback) iterates over every item in an array.
  • A callback is a function definition passed as an argument to another function.
  • Always start with a console.log() inside the .forEach() to visualize the shift from array to array item (you can skip that when you become used to it).
  • The .forEach() method will take your function definition and call it for every item of the array. Every time the callback is called, the first parameter will represent the corresponding array item.
  • Name your arrays in plural and the array item (inside the .forEach()) in singular.
  • Make sure to correctly place the return inside a function that contains a .forEach().