Skip to content

Latest commit

 

History

History
77 lines (55 loc) · 3.42 KB

File metadata and controls

77 lines (55 loc) · 3.42 KB

JavaScript array

📖 Deeper dive reading: MDN Array

JavaScript array objects represent a sequence of other objects and primitives. You can reference the members of the array using a zero based index. You can create an array with the Array constructor or using the array literal notation shown below.

const a = [1, 2, 3];
console.log(a[1]);
// OUTPUT: 2

console.log(a.length);
// OUTPUT: 3

Array functions

The Array object has several interesting static functions associated with it. Here are some of the interesting ones.

Function Meaning Example
push Add an item to the end of the array a.push(4)
pop Remove an item from the end of the array x = a.pop()
slice Return a sub-array a.slice(1,-1)
sort Run a function to sort an array in place a.sort((a,b) => b-a)
values Creates an iterator for use with a for of loop for (i of a.values()) {...}
find Find the first item satisfied by a test function a.find(i => i < 2)
forEach Run a function on each array item a.forEach(console.log)
reduce Run a function to reduce each array item to a single item a.reduce((a, c) => a + c)
map Run a function to map an array to a new array a.map(i => i+i)
filter Run a function to remove items a.filter(i => i%2)
every Run a function to test if all items match a.every(i => i < 3)
some Run a function to test if any items match a.some(i => i < 1)
const a = [1, 2, 3];

console.log(a.map((i) => i + i));
// OUTPUT: [2,4,6]
console.log(a.reduce((v1, v2) => v1 + v2));
// OUTPUT: 6
console.log(a.sort((v1, v2) => v2 - v1));
// OUTPUT: [3,2,1]

a.push(4);
console.log(a.length);
// OUTPUT: 4

☑ Assignment

Create a CodePen that defines a function named testAll that takes two parameters. The first parameter is an input array. The second parameter is a tester function that checks all the values of the input array. If the tester function returns true for each value in the input array, then testAll returns true.

Call testAll with an array of strings as the first parameter and an arrow function that returns true if the input has a length greater than 3.

Output the result of the call to testAll with the console.log function.

Here is a template for you to start with.

function testAll(input, tester) {
  const result = // Your code here
  return result
}

const result = testAll(/* Your parameters here */);

console.log(result);

If your section of this course requires that you submit assignments for grading: Submit your CodePen URL to the Canvas assignment.

Don't forget to update your GitHub startup repository notes.md with all of the things you learned and want to remember.

🧧 Possible solution

If you get stuck here is a possible solution.