Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript vs Python with respect to Python 'map()' function

In Python there is a function called map that allows you to go: map(someFunction, [x,y,z]) and go on down that list applying the function. Is there a javascript equivalent to this function?

I am just learning Python now, and although I have been told javascript is functional language, I can see that I have been programming in a non-functional javascript style. As a general rule, can javascript be utilized as a functional language as effectively as Python can? Does it have similar tricks like the map function above?

I've also just begun an SML course and am wondering how much of what I learn will be applicable to javascript as well.

like image 869
Dewey Banks Avatar asked Nov 08 '13 03:11

Dewey Banks


People also ask

Does JavaScript have a map function?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

What is a JavaScript map in Python?

Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable (tuple, lists, etc.). It is used when you want to apply a single transformation function to all the iterable elements. The iterable and function are passed as arguments to the map in Python.

Does Python have a map function?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.

What is the difference between Python and JavaScript?

KEY DIFFERENCES: JavaScript is a scripting language that helps you create interactive web pages, while Python is a high-level object-oriented programming language that has built-in data structures, combined with dynamic binding and typing, which makes it an ideal choice for rapid application development.


2 Answers

Sure! JavaScript doesn't have a lot of higher-order functions built-in, but map is one of the few that is built-in:

var numbers = [1, 2, 3];
var incrementedNumbers = numbers.map(function(n) { return n + 1 });
console.log(incrementedNumbers);  // => [2, 3, 4]

It might be worthwhile to note that map hasn't been around forever, so some rather old browsers might not have it, but it's easy enough to implement a shim yourself.

like image 147
icktoofay Avatar answered Sep 30 '22 05:09

icktoofay


You can also use underscore.js which adds tons of nice functionalists with only 4k size.

_.map([1, 2, 3], function(num){ return num * 3; });
//=> [3, 6, 9]
like image 28
Billy Chan Avatar answered Sep 30 '22 04:09

Billy Chan