JavaScript Equivalent of Python'S Zip Function

Is there a javacript async equivalent of python zip function?

Here's an async variation of my answer here:

async function* zip(...its) {

async function* iter(it) {
for await (let x of it)
yield x
}

its = its.map(iter)

while (true) {
let rs = await Promise.all(its.map(it => it.next()))
if (rs.some(r => r.done))
return
yield rs.map(r => r.value)
}
}

// demo:

let delay = (a, n) => {
console.log('begin', a)
return new Promise(r => setTimeout(() => {
console.log('resolved', a)
r()
}, n))
}

class Test {
constructor(start) {
this.start = start
}

async* [Symbol.asyncIterator]() {
for (let i = 1; i < 10; i++) {
await delay(this.start, Math.random() * 1000)
yield this.start + i
}
}
}

async function main() {
let iters = [
new Test('a'),
new Test('b'),
new Test('c'),
]

for await (let x of zip(...iters))
console.log('ZIP', ...x)
}

main()

How to map or zip a simple array to an array of arrays in JS with vanilla JS

You can use the second parameter passed in to the map function to know which index this element is at. Then pull the matching index from the other array. Since you want a resulting object, use fromEntries to wrap up the array that results from map.

const categories = [ "dairy", "fruit", "breakfast", "frozen" ];  
const codes = [['2340', '89878', '9998'], ['89878'], ['987979', '984', '29898', '299'], ['0008', '2988']];

const onSale = Object.fromEntries(
categories.map((cat, i) => [cat, codes[i]])
);

console.log(onSale)

Does a JS equivalent of Python's Multiple Variable Assignment exist?

In the question, you state that you cannot use Destructuring. However, Destructuring, more precisely an Array Destructuring Binding Pattern is exactly the right tool to use here, so you really should be using it. (Well, except for the fact that it is redundant, but more on that later.)

Here is how you would do a 1:1 translation of the Python code (Well, except for the fact that ECMAScript does not have Tuples) to ECMAScript:

function numbers(arr) {
if (arr.length <= 1) {
return arr;
}

const [leftHalf, rightHalf] = divide(arr);
return [leftHalf, rightHalf];
}

function divide(arr) {
const mid = Math.floor(arr.length / 2);
const left = arr.slice(0, mid);
const right = arr.slice(mid);

return [left, right];
}

The only difference of the ECMAScript code compared to the Python code is that in the Python code, both numbers and divide return a Tuple whereas ECMAScript does not have Tuples, so, in the ECMAScript code, they return Arrays.

However, note that in both the Python and the ECMAScript version, numbers destructures the return value of divide, only to put it back together with the exact same data structure, so you can just get rid of most of that code:

function numbers(arr) {
if (arr.length <= 1) {
return arr;
}

return divide(arr);
}
def numbers(arr):
if len(arr) <= 1:
return arr

return divide(arr)

You will also notice that I changed all your variables to consts in the ECMAScript code, since you are not modifying their bindings.

This API is weird and hard to use, though, because the numbers function returns two completely different things depending on the length of the argument array. It returns either an array of numbers or an array-of-arrays-of-numbers (in ECMAScript, in Python, it returns a tuple-of-arrays-of-numbers). This makes it harder for the caller to use since the different return types need to be treated differently.

How do I zip two arrays in JavaScript?

Use the map method:

var a = [1, 2, 3]

var b = ['a', 'b', 'c']

var c = a.map(function(e, i) {

return [e, b[i]];

});

console.log(c)

Systematacally combining arrays

Do like:

const a = ['one', 'two', 'three'], b = ['a', 'b', 'c'], c = ['1', '2', '3'], combo = [];
for(let i=0,l=a.length; i<l; i++){
combo.push([a[i], b[i], c[i]]);
}
console.log(combo);


Related Topics



Leave a reply



Submit