Home > Enterprise >  How to add items of arrays to end of array?
How to add items of arrays to end of array?

Time:04-11

There is sourceArray and some additionalArray. Need to add items from additionalArray to the end of sourceArray. And in result sourceArray contains all items (no create new array). The problem is items count of additionalArray may be thousands.

// example
push([], [1, 2, 3], [10, 20, 30]) // [1, 2, 3, 10, 20, 30]
push(['a', 'b'], 'x', ['z', '0']) // ['a', 'b', 'x', 'z', '0']
// my solution
function push(sourceArray, ...additionalArray) {
    additionalArray.forEach((array) => {
        array = Array.isArray(array) ? array : [array];
        if (array.length < 1000) {
            sourceArray.push.apply(sourceArray, array);
        } else {
            array.forEach((item) => sourceArray.push(item));
        }
    });
    return sourceArray;
}

My question is there more elegant solution for this task?

CodePudding user response:

As of MDN, you can use the array spread syntax:

let vegetables = ['parsnip', 'potato']
let moreVegs = ['celery', 'beetroot']

// Merge the second array into the first one
vegetables.push(...moreVegs);

console.log(vegetables)  // ['parsnip', 'potato', 'celery', 'beetroot']

CodePudding user response:

You might find using .flat() can help you here. If you use that on the arguments following your source that you want to push into, you can then spread that result into a call to .push():

const push = (source, ...rest) => {
  source.push(...rest.flat());
  return source;
}

console.log(push([], [1, 2, 3], [10, 20, 30])) // [1, 2, 3, 10, 20, 30]
console.log(push(['a', 'b'], 'x', ['z', '0'])) // ['a', 'b', 'x', 'z', '0']

This does have a limitation though in that .push() can only accept a certain amont of arguments. You might hit the max argument limit and this can throw. Using .reduce() or a for loop would help with that:

const push = (source, ...rest) => {
  for(const item of rest.flat())
    source.push(item)
  return source;
}

console.log(push([], [1, 2, 3], [10, 20, 30])) // [1, 2, 3, 10, 20, 30]
console.log(push(['a', 'b'], 'x', ['z', '0'])) // ['a', 'b', 'x', 'z', '0']

CodePudding user response:

Assuming the OP wants to only flat one level of the arrays, we can use the function Array.prototype.push along with the function Array.prototype.flat.

function push(source, ...additional) {
  source.push(...additional.flat());
  return source;
}

console.log(push([], [1, 2, 3], [10, 20, 30])) // [1, 2, 3, 10, 20, 30]
console.log(push(['a', 'b'], 'x', ['z', '0'])) // ['a', 'b', 'x', 'z', '0']

  • Related