From time to time I google for the right syntax how to process lists and dictionaries in Python or arrays and objects in JavaScript. So I decided to extend my series of equivalents with those functions. After all, it's me too, who will be using the information I provide here.
All truthful elements
Sometimes we need to check from a list of conditions if all of them are true, or from a list of elements if all of them are not empty.
This can be checked with the following in Python:
items = [1, 2, 3]
all_truthy = all(items)
# True
And here is an equivalent in JavaScript:
items = [1, 2, 3];
all_truthy = items.every(Boolean);
// true
Any truthful elements
Similarly, we can check if at least one of the conditions is true, or there is at least one non-empty element in a list.
It Python we would do that with:
items = [0, 1, 2, 3]
some_truthy = any(items)
# True
And in JavaScript we would check it like this:
items = [0, 1, 2, 3];
some_truthy = items.some(Boolean);
// true
Iterate through each element and its index
Here is an example of how to iterate through a list of items and also check their indices in Python. It is useful for verbose console output when creating different command line tools that process data:
items = ['a', 'b', 'c', 'd']
for index, element in enumerate(items):
print(f'{index}: {element};')
In JavaScript an analogous way to do the same would be using the forEach()
method. The usual for
loop is also an option, but I find the forEach()
more elegant and clear.
items = ['a', 'b', 'c', 'd'];
items.forEach(function(element, index) {
console.log(`${index}: ${element};`);
});
Map elements to the results of a function
To process all elements of a list, you can either iterate through them with the for
loop and create a new list with modifications, or you can do that in one step by mapping the list items to a modification function. In Python this can be done with the map()
function:
items = [0, 1, 2, 3]
all_doubled = list(map(lambda x: 2 * x, items))
# [0, 2, 4, 6]
In JavaScript the map()
is a method of an array:
items = [0, 1, 2, 3];
all_doubled = items.map(x => 2 * x);
// [0, 2, 4, 6]
Filter elements by a function
When you need to search for some elements in a list or array and want to avoid for
loops, you can use the filtering functionality. In Python that is doable with the filter()
function that accepts the filtering function and the list and returns a new filtered list.
items = [0, 1, 2, 3]
only_even = list(filter(lambda x: x % 2 == 0, items))
# [0, 2]
In JavaScript there is a filter()
method of the array for that.
items = [0, 1, 2, 3];
only_even = items.filter(x => x % 2 === 0);
// [0, 2]
In both cases, the filtering function checks each item if it is matching the filter criteria and returns true in that case.
Reduce elements by a function to a single value
When you want to apply some function to a list of items to get a single result in one go, you can use the reduce function. It works for summing, multiplying, ORing, ANDing, or checking maximums and minimums.
In Python there is a reduce()
function for that.
from functools import reduce
items = [1, 2, 3, 4]
total = reduce(lambda total, current: total + current, items)
# 10
In JavaScript there is a reduce()
method of the array.
items = [1, 2, 3, 4];
total = items.reduce((total, current) => total + current);
// 10
Merge dictionaries
There are multiple ways to merge dictionaries in Python or objects in JavaScript. But these are probably the simplest ones.
In Python it's decomposing dictionaries to tuples of keys and arrays, joining them, and creating a new dictionary.
d1 = {'a': 'A', 'b': 'B'}
d2 = {'a': 'AAA', 'c': 'CCC'}
merged = dict(list(d1.items()) + list(d2.items()))
# {'a': 'AAA', 'b': 'B', 'c': 'CCC'}
Analogously, in JavaScript it's spreading two objects into a new object:
d1 = {a: 'A', b: 'B'}
d2 = {a: 'AAA', c: 'CCC'}
merged = {...d1, ...d2};
// {a: 'AAA', b: 'B', c: 'CCC'}
The Takeaways
- In both languages, you can traverse through lists of items without explicitly incrementing and referencing an index.
- For processing list items, you don't necessarily need a loop. The dedicated methods or functions
all() / every()
,any() / some()
,map()
,filter()
, andreduce()
are there to help you. - In both languages, you can merge multiple dictionaries into one. If the same key appears in several dictionaries, the latest one will be used in the merged dictionary.
Of course, I also updated the cheat sheet with the full list of equivalents in Python and JavaScript that you saw here described. This cheat sheet helps me with a good overview next to my laptop, so I believe that it would be helpful to you too. The new revision 10 is with syntax highlighting, so it makes it even better to explore and understand.
Get the Ultimate Cheat Sheet of Equivalents in Python and JavaScript
Use it for good!
Cover photo by Darren Chan.
Good poost
ReplyDelete