JavaScript Fundamentals: Arrays

Day 10, 11 & 12 of #100DaysOfCode

Arrays

const numbers = [1, 2, 3, 4];
const booleans = [true, false, true];
const strings = ["happy", "laugh"];
const nested = [[2, 3, [2, 3]], 3];
const result = average([80,90,98,100]); 
console.log( result ); // 92
function sumEven(array) {
let sum = 0;
for(let i = 0; i < array.length; i++){
if(array[i] % 2 === 0){
sum = sum + array[i]
}
}
return sum;
}

Array Indexing

const element = array[0];
function hasOne(array) {
for(let i=0; i<array.length; i++){
if(array[i] === 1){
return true;
}
}
return false;
}

Return New Array

function greaterThanFour(array) {
const newArray = [];
for(let i = 0; i < array.length; i++) {
const element = array[i];
// is this element greater than 4?
if(element > 4) {
// yes, push this element on our array
newArray.push(element);
}
}
return newArray;
}
function unique(array) {
let newArray = [];
for(let i = 0; i < array.length; i++) {
const element = array[i];
if (newArray.indexOf(element) === -1) {
// indexOf method was learned in previous tutorial
newArray.push(element);
}
}
return newArray;
}

Modify Array Values

const array = [1,2,3];
array[0] = 6;
console.log(array); // [6,2,3]
function addOne(array) {
for(let i = 0; i < array.length; i++) {
array[i]++;
}
}

Modify Array

const array = [1,2,3];
for(let i = 0; i < array.length; i++) {
if(array[i] > 1) {
array.splice(i, 1);
}
}
console.log(array); // [1, 3]

// This is a Bug🐛
const array = [1,2,3];
for(let i = array.length - 1; i >= 0; i--) {
if(array[i] > 1) {
array.splice(i, 1);
}
}
console.log(array); // [1]

Conclusion

--

--

Student | Content Creator | Explorer and Learner

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store