Joining index-based JavaScript arrays without .concat

I am trying to combine two arrays, and most of the answers involve adding a second array to the end of the first. I need to combine index into index.

Here is a sample code:

let arr1 = ['golf', 'hockey', 'tennis'];
let arr2 = ['player1', 'player2', 'player3'];

Array.prototype.zip = function (arr) {
  return this.map(function (e, i) {
    return [ e, arr[i]];
  })
};
const arr3 = arr1.zip(arr2);
console.log(arr3);
Run code

The result should be:

['golf', 'player1', 'hockey', 'player2', 'tennis', 'player3']

The above code looks as if it works, but does not work. If it can be fixed or exchanged for the best, that would be great .....

+4
source share
4 answers

You can use .reduce()both arrays for zip:

let arr1 = ['golf', 'hockey', 'tennis'],
    arr2 = ['player1', 'player2', 'player3'];

let zip = (a1, a2) => a1.reduce((a, c, i) => (a.push(c, a2[i]), a), []);

console.log(zip(arr1, arr2));
Run code

Docs:

+3
source

.map : 3 , .map , 3 . concat, .reduce .map, :

const arr1 = ['golf', 'hockey', 'tennis'];
const arr2 = ['player1', 'player2', 'player3']

Array.prototype.zip = function (otherArr) {
  return this.reduce((accum, item, i) => {
    accum.push(item);
    accum.push(otherArr[i]);
    return accum;
  }, []);
};
const arr3 = arr1.zip(arr2)
console.log(arr3)

, Array. , :

const arr1 = ['golf', 'hockey', 'tennis'];
const arr2 = ['player1', 'player2', 'player3']

function zip(arr1, arr2) {
  return arr1.reduce((accum, item, i) => {
    accum.push(item);
    accum.push(arr2[i]);
    return accum;
  }, []);
};
const arr3 = zip(arr1, arr2);
console.log(arr3);
0

.

let arr1 = ['golf', 'hockey', 'tennis'];
let arr2 = ['player1', 'player2', 'player3']

Array.prototype.zip = function (arr) {
    this.map(function (e, i) { this.splice(i*2+1, 0, arr[i]); }, this )
};
const arr3 = arr1.zip(arr2)
console.log(arr3)
0

: , , ():

let arr1 = ['golf', 'hockey', 'tennis'];
let arr2 = ['player1', 'player2', 'player3']

Array.prototype.zip = function (arr) {
      return this.map(function (e, i) {
          return [ e, arr[i]]
      }).reduce((a,b)=>a.concat(b)); // blink and you miss the change...
    };
const arr3 = arr1.zip(arr2)
console.log(arr3)

This approach preserves what you have and does not contain many complexities, such as additional method calls, temp arrays, etc .; what is the beauty of a functional approach: you are one chain link from what you need. I would also convert it to the stand method, instead of modifying the prototype, but away from the point ...

0
source

Source: https://habr.com/ru/post/1696298/


All Articles