Home > Software engineering >  Array Extend without custom method?
Array Extend without custom method?

Time:03-08

Is it possible to use Array.push to add multiple values from a list? For example, currently what I'm having to do is:

Array.prototype.extend = function(arr) {
    for (let elem of arr) {
        this.push(elem);
    }
}
let x = [1,2,3];
let y = [4,5,6];
let z = [7,8,9];
x.push(y);
x.extend(z)
console.log(x);

Or, is there some way to pass the array as a single argument to the push method, or perhaps there's another Array method entirely that does this instead?

CodePudding user response:

you can spread the array element like this

const x = [1,2,3];
const y = [4,5,6];
const z = [7,8,9];
x.push(...y);
x.push(...z)
console.log(x);

CodePudding user response:

You can push multiple arguments to Array.prototype.push and they'll all be pushed to our result array, so we can "convert" our array into multiple arguments using the ES6 spread syntax.

let x = [1,2,3];
let y = [4,5,6];
x.push(...y);
console.log(x);

CodePudding user response:

It's usually bad practice to Extend Native Types with Custom Methods. So instead of adding custom ones to the Array prototype you could:

const x = [1,2,3];
const y = [4,5,6];
const z = [7,8,9];
x.push(y);
x.push(...z)
console.log(x);

let x = [1,2,3];
const y = [4,5,6];
const z = [7,8,9];
x.push(y);
x = x.concat(z);
console.log(x);

The difference being - .concat() does not directly modify the original Array, therefore the x = x.concat( assignment syntax, and the Original x array being set as a let variable.

  • Related