Understand the idea
An array stores an ordered collection of values. Indexing starts at 0. For a dense array such as the example, length is the number of items; sparse arrays can contain empty slots, so length is not always the count of actual entries.
filter creates a new array containing values that pass a test. map creates a new array by transforming each value. These operations do not directly change the original array, although objects inside the arrays may still be shared references.
Read the example
This is a JavaScript fragment. Run it in a browser console or an external script. Supply any HTML or data file named in the example first.
const places = ["Erfurt", "Berlin", "Amsterdam"];
const shortNames = places.filter(place => place.length < 7);
console.log(shortNames); // ["Erfurt", "Berlin"]
console.log(places.length); // 3A small mistake, explained
What goes wrong
Using array.length as the last index goes one place beyond the final item.
How to fix it. The last index is length - 1. Handle the empty-array case, which has no final item.
Try it yourself
Add another city and change the filter condition. Check that places still contains the complete collection.
Further reading
ECMAScript — Array.prototype.filter
Keep exploring
- JavaScript · Guide
Variables & valuesGive a value a name and understand when it can change.
- JavaScript · Guide
Conditions & comparisonsMake a decision without accidentally changing the value.