这是indexloc提供的服务,不要输入任何密码
Skip to content

View Examples

Sebastian Raff edited this page Sep 30, 2017 · 3 revisions

These examples operate on data created by create-example-data.js.

Get all moons and their planet in alphabetical order

Map

if (this.type === 'Moon') {
    emit({name: this.name, planet: this.planet})
}

Reduce

return result.sort((a, b) => a.name.localeCompare(b.name))

Get the biggest moon of all planets

Map

if (this.type === 'Moon') {
  emit({
    name: this.name,
    diameter: this.diameter,
    planet: this.planet
  })
}

Reduce

const out = {};

result.forEach(moon => {
    if (!out[moon.planet] || moon.diameter > out[moon.planet].diameter) {
        out[moon.planet] = {name: moon.name, diameter: moon.diameter}
    }
});

return out;

Get all planets and count their moons

Map

if (this.type === 'Moon') {
  emit(this.planet)
}

Reduce

return result.reduce((acc, curr) => {
  acc[curr] = (acc[curr] || 0) + 1
  return acc
}, {})

Get all planets and count their moons, output as array, order by descending moon count

Map

if (this.type === 'Moon') {
    emit(this.planet)
}

Reduce

const count = result.reduce((acc, curr) => {
    acc[curr] = (acc[curr] || 0) + 1
    return acc
}, {})

return Object.keys(count)
	.map(planet => ({planet, moons: count[planet]}))
	.sort((a, b) => a.moons < b.moons)

Clone this wiki locally