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?

2
  • You could use return (value !== Object(value)); to determine if it is primitive. jsfiddle.net/kieranpotts/dy791s96 Commented Apr 4, 2019 at 5:55
  • Kind of weird to be wanting to do that. Primitives behave a lot like immutable objects. Commented Apr 4, 2019 at 6:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Functions aren’t primitives, but they have a typeof of "function". Also, typeof null === "object".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.