Home › JavaScript Tutorial › JS arrays
JS arrays
Lists and their methods.
push, pop, slice, sort, find, filter, map and reduce cover most work.
Commands in this lesson
push
Definition: Adds an item to the end of an array.
Syntax:
array.push(item);
Example:
const a = [1, 2];
a.push(3);
console.log(a);filter
Definition: Builds a new array with only the items that pass a test.
Syntax:
array.filter(function);
Example:
console.log([1, 2, 3, 4].filter(function(x){ return x % 2 === 0; }));map
Definition: Builds a new array by transforming each item.
Syntax:
array.map(function);
Example:
console.log([1, 2, 3].map(function(x){ return x * 2; }));Example code
<pre id='o'></pre>
<script>
const a=[5,1,4];a.push(9);
o.textContent=[a.sort((x,y)=>x-y),a.map(x=>x*2),a.filter(x=>x>3),a.reduce((s,x)=>s+x,0),a.indexOf(4)].join('\n');
</script>