Merge Arrays in JavaScript

Merging is an activity that involves considering two or more lists (preferably sorted) as input to a program and expecting a single list as an output. The output represents all the elements from the input lists (in a sorted order).

Merging Arrays

In JavaScript, a list of elements can be represented through an Array. This blog post covers different ways in which lists can be merged.

🔗 Combine two arrays using push function. Push operation can be destructive based on its usage, meaning it can mutate an existing list.

Array.prototype.push.apply(tropicalFruitsBasket, nonTropicalFruitsBasket)

const fruitsBasket = []
fruitsBasket.push(...tropicalFruitsBasket, ...nonTropicalFruitsBasket)

🔗 Combine two arrays using ES6 spread operator.

const tropicalFruitsBasket = ['Rambutan', 'Soursop', 'Salak', 'Mangosteen', 
                        'Breadfruit', 'Ackee', 'Durian', 'Babaco']

const nonTropicalFruitsBasket = ['Apple', 'Pear', 'Almond', 'Peach', 'Nectarine', 'Apricot', 
                           'Plum', 'Strawberry', 'Sloe', 'Cherry']

const fruitsBasket = [...tropicalFruitsBasket, ...nonTropicalFruitsBasket]

const fruitsBasket = Array.of(...tropicalFruitsBasket, ...nonTropicalFruitsBasket)

🔗 Combine two arrays using concat function.

The concat function returns a new array.

const fruitsBasket = nonTropicalFruitsBasket.concat(tropicalFruitsBasket)

const fruitsBasket = [].concat(nonTropicalFruitsBasket, tropicalFruitsBasket)

🔗 Combine two arrays using reduce and concat functions.

const fruits = nonTropicalFruitsBasket.reduce((acc, cv) => acc.concat(cv), tropicalFruitsBasket)

🔗 Combine two arrays using reduce and push functions.

const fruits = nonTropicalFruitsBasket.reduce((acc, cv) => {
	acc.push(cv)
	return acc
}, tropicalFruitsBasket)

🔗 Combine two arrays using a for-loop.

const fruits = []
for (let fruit of nonTropicalFruitsBasket) {
  fruitsBasket.push(fruit)
}
for (let fruit of tropicalFruitsBasket) {
  fruitsBasket.push(fruit)
}

/**
 * a better way would be to use a function which adds fruit elements to basket
 * @param {sourceBasket} source basket
 * @param {targetBasket} target basket
 */

function addFruits(sourceBasket, targetBasket) {
  for (let fruit of sourceBasket) {
    targetBasket.push(fruit)
  }
  return targetBasket
}
const fruits = addFruits(tropicalFruitsBasket, nonTropicalFruitsBasket)

All the above code snippets yield below output:

// `fruits` yields
[
  'Rambutan',   'Soursop',
  'Salak',      'Mangosteen',
  'Breadfruit', 'Ackee',
  'Durian',     'Babaco',
  'Apple',      'Pear',
  'Almond',     'Peach',
  'Nectarine',  'Apricot',
  'Plum',       'Strawberry',
  'Sloe',       'Cherry'
]

🔗 Combine multiple arrays is better handled through functions.

function combineArrays(...arrays) {
  const result = [];
  for (let array of arrays) {
    result.push(...array)
  }
  return result;
}

The above function can be shortened with a reduce and conat functions.

function combineArrays(...arrays) {
  return arrays.reduce((acc, cv) => acc.concat(cv), [])
}

Snippets

use spread operator to convert string to array of characters/strings
> [...'Breadfruit']
[
  'B', 'r', 'e', 'a',
  'd', 'f', 'r', 'u',
  'i', 't'
]

// split a string and join it back into a comma-separated string
> [...'Breadfruit'].join()
'B,r,e,a,d,f,r,u,i,t'

// split a string and join it back into a string. 
// identity function -> f(x) = x; holds for all x: string
> [...'Breadfruit'].join('')
'Breadfruit'

// combine arrays with numbers and a string
> [...[1, 2, 3], ...['random']]
[ 1, 2, 3, 'random' ]

> [...[1, 2, 3, 'random'], ...['random']]
[ 1, 2, 3, 'random', 'random' ]

// Don't do this! Spread operator spreads a string
> [...[1,2,3], ...'random']
[
  1,   2,   3,   'r',
  'a', 'n', 'd', 'o',
  'm'
]

// array with a hole
> [...[1, , 3]]
[ 1, undefined, 3 ]

// a hole from an array can be removed by filter
> [...[1, , 3].filter(i => true)]
[ 1, 3 ]

// flatten an array of arrays using concat function
// in a sense, we are actually combining multiple arrays here.
> [[0, 1], [2, 3], [4, 5]].reduce((acc, cv) => acc.concat(cv), [])
[ 0, 1, 2, 3, 4, 5 ]

Links

© 2023 Kranthi Lakum. All rights reserved.