Published
Edited
Nov 18, 2019
Map, Filter, Reduce
Insert cell
md`# Map, Filter, Reduce`
Insert cell
md`# Map`
Insert cell
a = [1,2,3,4,5]
Insert cell
b = a.map(function(e){
return e;
})
Insert cell
hoteles = [
{name:"Hilton", stars: 5, precios:[80,150,190], piscina:true},
{name:"Posada Pepe", stars: 3, precios:[30,40,60], piscina:false},
{name:"NH", stars: 4, precios:[60,60,90],piscina:false},
{name:"Casa de Papa", stars:5, precios:[0], piscina:true}
]
Insert cell
{
let nombres = ""
for(let i=0; i<hoteles.length; i++){
nombres += hoteles[i].name + ","
}
return nombres;
}
Insert cell
{
let nombres = []
for(let i=0; i<hoteles.length; i++){
nombres.push(hoteles[i].name)
}
return nombres.join(', ');
}
Insert cell
hoteles.map(function(hotel){
return hotel.name;
})
Insert cell
hoteles.map(function(hotel){
return hotel.name;
}).join(',')
Insert cell
md`# Filter`
Insert cell
hoteles.filter(function(hotel){
if(hotel.name == "NH"){
return false;
}
return true;
})
Insert cell
hoteles.filter(function(hotel, index, array){
console.log(hotel, index, array)
return hotel.piscina;
})
Insert cell
// Nombres Hoteles con piscina
hoteles.filter(function(hotel){
return hotel.piscina;
}).map(function(hotel){
return hotel.name + "(" +"*".repeat(hotel.stars) + ")";
}).join(',')
Insert cell
"Hola".repeat(4)
Insert cell
md`# Reduce 🤷🏼‍♂️`
Insert cell
a
Insert cell
a.reduce(function(acc,e){
console.log(acc,e)
return "pepe";
},0)
Insert cell
a.reduce(function(acc,e){
console.log(acc,e)
return "pepe";
})
Insert cell
// La suma
a.reduce(function(acc,e){
console.log(acc,e)
return acc+e;
})
Insert cell
// La media
a.reduce(function(acc,e){
console.log(acc,e)
return acc+e;
})/a.length
Insert cell
// La media v2
a.reduce(function(acc, e, index, array){
console.log(acc, e, index, array)
return acc+(e/array.length);
},0)
Insert cell
z = [1,2,3,4,3]
Insert cell
// El maximo
z.reduce(function(acc,e){
if(acc > e) return acc;
return e;
})
Insert cell
hoteles
Insert cell
hoteles.reduce(function(acc,hotel, index){
if(hotel.piscina){
if(index != 0){
return acc + ", " + hotel.name;
}else{
return acc + hotel.name;
}
}
return acc;
},"")
Insert cell
{
function imprime(e){
console.log(e);
}
[1,2,3,4].forEach(imprime)
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more