Equivalents in Python and JavaScript. Bonus
Tags: basics, intermediate, javascript, python
Published: 2019-02-02 23:46:45

---
title: Equivalents in Python and JavaScript. Bonus
published: true
tags: Basics,Intermediate,JavaScript,Python
canonical_url: http://djangotricks.blogspot.com/2019/02/equivalents-in-python-and-javascript-bonus.html
series: Equivalents in Python and JavaScript
---

 ![](https://3.bp.blogspot.com/-AbBqknEOT04/XFYb-oh0udI/AAAAAAAAB7w/d9zY2pG0O8IG2-D75GUkyT8RjckJU5FKACLcBGAs/s1600/equivalents-in-python-and-javascript-bonus.png) 

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__:

```python
items = [1, 2, 3]
all_truthy = all(items)
# True
```

And here is an equivalent in __JavaScript__:

```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:

```python
items = [0, 1, 2, 3]
some_truthy = any(items)
# True
```
And in __JavaScript__ we would check it like this:

```javascript
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:

```python
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.

```javascript
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:

```python
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:

```javascript
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.

```python
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.

```javascript
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.

```python
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.

```javascript
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.

```python
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:

```javascript
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()`, and `reduce()` 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.

<center><a href="https://www.djangotricks.com/goodies/YbnpiLKBmAZi/" target="_blank">✨✨✨<br />Get the Ultimate Cheat Sheet of<br />Equivalents in Python and JavaScript<br />✨✨✨</a></center>

Use it for good!

---
Cover photo by [Darren Chan](https://unsplash.com/photos/0nHOfjH0emE).