JS: Apply Array Method to Array-Like Object

By Xah Lee. Date: . Last updated: .

to apply Array methods to Array-Like Object, do:

Reflect.apply(arrayMethod, ArrayLikeObj, [arrayMethodArgs]);

γ€”see Reflect.apply〕

// using a array method Array.prototype.map directly on array-like object

const arLike = { 0: "a", 1: "b", 2: "c", length: 3 };

function ff(x) {
  return x + "z";
}

const xResult = Reflect.apply(Array.prototype.map, arLike, [ff]);

// result is a array
console.log(Array.isArray(xResult));

xResult;
// [ "az", "bz", "cz" ]

or do:

arrayMethod.call(ArrayLikeObj, arrayMethodArgs)

γ€”see Function.prototype.call〕

// using a array method Array.prototype.map directly on array-like object

const arLike = { 0: "a", 1: "b", 2: "c", length: 3 };

function ff(x) {
  return x + "z";
}

const xResult = Array.prototype.map.call(arLike, ff);

// result is a array
console.log(Array.isArray(xResult));

JavaScript, Array-Like Object