Tools for working with arrays

INPUT · Slides

Rebuilding every item

01 / 05

Not choosing but rebuilding

filter was the method that chooses what matches. The contents stay as they are; only the number falls.

But when you want every price with tax added, or everyone's name with a label on it, what you want is an array with the same number and changed contents.

02 / 05

map lines up the converted results

The function you hand map returns the value after conversion. map gathers those return values into a new array.

filter returns a condition, map returns the converted value. What you return is the only difference.

const nums = [1, 2, 3];const twice = (n) => {  return n * 2;};console.log(nums.map(twice));

Result

[2, 4, 6]

03 / 05

The number of items does not change

map sends one back per entry, so the number of items is always the same. It never falls or grows.

And the original array does not change. As with filter, it only makes a new array and sends it back.

const nums = [1, 2, 3];const plusTen = (n) => {  return n + 10;};const result = nums.map(plusTen);console.log(result);console.log(result.length);console.log(nums);

Result

[11, 12, 13]
3
[1, 2, 3]

04 / 05

The kind may change

The converted value need not be the same kind as the original. You can make an array of strings out of an array of numbers.

Only strings show with double quotes, so you can see by eye that the kind changed.

const nums = [1, 2, 3];const toText = (n) => {  return `no.${n}`;};console.log(nums.map(toText));

Result

["no.1", "no.2", "no.3"]

05 / 05

Pull out only the part you want

Making an array of one property out of an array of objects is another of map's specialities.

Forget the return and the converted value is never settled, so you get a row of undefined. When it will not work, look for the return first.

Right — let us rebuild some.

const items = [  { name: "pen", price: 120 },  { name: "notebook", price: 180 },];const toName = (item) => {  return item.name;};console.log(items.map(toName));

Result

["pen", "notebook"]