filter, map, reduce with js and python (There are also arrow expressions, lambda expressions, comprehension expressions)

Introduction

I make a web application with python and it always mixes, so make a note.

JavaScript

Full version

var orig = [{id: '0000', value: 0},
            {id: '0001', value: 1},
            {id: '0002', value: 2}];
 
// filter
var filtered = orig.filter( function(el,idx,ary) {
  return el.id=='0001';
});
// [{id: '0001', value: 0}]
 
// map
var mapped = orig.map( function(el,idx,ary) {
  return el.value;
});
// [0, 1, 2]
 
// reduce
var reduced = mapped.reduce( function(hist,el,idx,ary) {
  return hist+el;
});
// 3
 
//Direct rewrite
$.each(orig, function(idx,el) {
  el.value += 100;
});
// [{id: '0000', value: 100},
//  {id: '0001', value: 101},
//  {id: '0002', value: 102}]

El is each element, idx is an index, and ary is the original array. idx and ary of filter, map and reduce can be omitted.

Arrow type

// filter
var filtered2 = orig.filter( el => el.id=='0001' );
 
// map
var mapped2 = orig.map( el => el.value );
 
// reduce:lambda expression
var reduced2 = mapped2.reduce( (hist,el) => hist+el );
 
//Direct rewrite
$.each(orig, (idx,el) => { el.value+100 } );

hist of reduce is the execution result of the calculation so far.

Python

lambda expression

orig = [{'id': '0000', 'value': 0},
        {'id': '0001', 'value': 1},
        {'id': '0002', 'value': 2}]
 
# filter
filtered = filter(lambda el: el['id']=='0001', orig)
 
# map
mapped = map(lambda el: el['value'], orig)
 
# reduce
reduced = reduce(lambda hist,el: hist+el, mapped)

Intensional expression

# filter
filtered2 = [ el for el in orig if el['id']=='0001' ]
 
# map
mapped2 = [ el['value'] for el in orig ]

Other cautions

How to access the object

--JavaScript is ʻobject.key --Python is ʻobject ['key']

About JavaScript arrow expressions

//Uninflected word
function(param1, ..., paramN) { statements }
(param1, ..., paramN) => { statements }
 
//If you want to return the value{}Can be omitted.
function(param1, ..., paramN) { return expression; }
(param1, ..., paramN) => { return expression; }
(param1, ..., paramN) => expression
 
//With one argument()Can be omitted.
(param) => { statements }
param => { statements }

Recommended Posts

filter, map, reduce with js and python (There are also arrow expressions, lambda expressions, comprehension expressions)
python string processing map and lambda
Try to make foldl and foldr with Python: lambda. Also time measurement
Effective Python memo Item 7 Use list comprehension instead of map and filter
Python comprehension (list and generator expressions) [additional]
What are you comparing with Python is and ==?
Dynamic HTML pages made with AWS Lambda and Python
Writing using lambda expressions and filter functions and writing using list comprehensions
Investigate Java and python data exchange with Apache Arrow
Make ordinary tweets fleet-like with AWS Lambda and Python