0

I have an update method that should update an item in array:

function update(array) {
  return array.map(item => {
    // item or primitive?
  })
}

What is the best way (in terms of reliability and performance) to distinguish if it's an array of objects or primitive values?

undefined
  • 6,366
  • 12
  • 46
  • 90
  • You could use `return (value !== Object(value));` to determine if it is primitive. http://jsfiddle.net/kieranpotts/dy791s96/ – ABC Apr 04 '19 at 05:55
  • Kind of weird to be wanting to do that. Primitives behave a lot like immutable objects. – Ry- Apr 04 '19 at 06:02

1 Answers1

0

You are use every() and typeof operator

let prim = [1,2,3];
let arrOfObjs = [{a:1},{b:2}];

function isArrayOfObjs(arr){
  return arr.every(x => typeof x === "object");
}

console.log(isArrayOfObjs(prim))   //false
console.log(isArrayOfObjs(arrOfObjs)) //true
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • Functions aren’t primitives, but they have a `typeof` of `"function"`. Also, `typeof null === "object"`. – Ry- Apr 04 '19 at 06:04