unicornsfartpixels is an online notebook cataloguing the always expanding web development landscape & creative side of code.

March 01, 2018

.map() vs p5.js map()

The array’s integrated map method and p5’s map method are not to be confused. Maybe no one needs this reminder other than me but since I got comfortable with p5’s map() method before I really got my hands dirty with vanilla javascript’s built in Array.prototype.map(), I’ve tricked myself more than once into thinking that map() took an array and made it fit into a range that previously wasn’t available to it. If you find that confusing, welcome to my world. Turns out I had mashed both map()’s uses into one hodgepodge of disfunction. So let’s sort things out:

Array.prototype.map()

map() takes an array and executes a function you provide on every element in the array, returning a new array that contains the results.

const books = [
  {
    title: 'Shantaram',
    genre: 'nonfiction',
    pages: 933,
  },
  {
    title: 'Mindstorms',
    genre: 'nonfiction',
    pages: 252,
  },
  {
    title: 'A Beautiful Question',
    genre: 'nonfiction',
    pages: 448,
  },
  {
    title: 'The Goldfinch',
    genre: 'fiction',
    pages: 771,
  },
]

let bookGenres = books.map((book, index, books) => {
  return book.genre
})

// bookGenres = ["nonfiction", "nonfiction", "nonfiction", "fiction"]

p5’s map()

map() tracks a value in one range and mirrors it’s behaviour in a new range.

// map(value,start1,stop1,start2,stop2)

var value = 10
var m = map(value, 0, 100, 0, width)
ellipse(m, 50, 10, 10)

See the Pen p5 map() ex by Eliza SJ (@elizasj) on CodePen.

To recap…

Vanilla js’.map() is one of the first things you’re taught when you dive into functional js because it can be used as a really handy replacement for a for loop. Whereas p5’s .map() works more like the kind you’d use to explore a new city - it converts the scale of a range to fit into another.