-3

I wanted to join 2 arrays of the same length. However I want to join each element of with it's counterpart and produce a new array with the combined values.

// will always be string
var array = [a, b, c, d] 

// Will always be number
var array2 = [1, 2, 0, 4,] 

var output = [a1, b2, c0, d4]

I then want to edit the output array removing any values of 0. So my final output should be:

var result = [a1, b2, d4] 

Any thoughts and suggestions much appreciated.

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
ashToronto
  • 45
  • 3
  • 6
  • 4
    Please go read [ask], and show us what you have tried so far. – CBroe Feb 27 '18 at 09:47
  • Possible duplicate of [Javascript equivalent of Python's zip function](https://stackoverflow.com/questions/4856717/javascript-equivalent-of-pythons-zip-function) – Mureinik Feb 27 '18 at 09:49
  • Do you have to have the output array or can you skip straight to the result? – Matt Feb 27 '18 at 13:32

3 Answers3

3

Use map and filter

var result = array.map( (s, i) => [s , array2[i]] ) //combine values
                  .filter( s => s[1] != 0 ) //filter out 0s
                  .map( s => s.join("") ); //join them

Demo

// will always be string
var array = ["a", "b", "c", "d"];

// Will always be number
var array2 = [1, 2, 0, 4, ];

var result = array.map((s, i) => [s, array2[i]]) //combine values
  .filter(s => s[1] != 0) //filter out 0s
  .map(s => s.join("")); //join them

console.log(result);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

Check this repl: https://repl.it/@Freundschaft/MeagerNocturnalFormats

// will always be string
var array = ["a", "b", "c", "d"] 

// Will always be number
var array2 = [1, 2, 0, 4,] 

function joinArraysCustom (firstArray, secondArray){
  if(firstArray.length !== secondArray.length){
    throw new Error('Arrays must match');
  }
  return firstArray.map(function(value, index){
    return "" + value + secondArray[index];
  }).filter(value => !value.endsWith('0'))
}

console.log(joinArraysCustom (array, array2));
Qiong Wu
  • 1,504
  • 1
  • 15
  • 27
0

You may use .reduce() and .push():

var arr1 = ['a', 'b', 'c', 'd'];
var arr2 = [1, 2, 0, 4];

function createArray(s, n) {
  return n.reduce((a, c, i) => (
    /* combine and push if current value is not zero
     * otherwise return same array
     */
    c != 0 ? (a.push(c + s[i]), a) : a
  ), []);
}

console.log(createArray(arr1, arr2));

Useful Resources:

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95