1

I have an array of objects and there is the property id which may contains integers or strings. I'm using that property to compare, but now I'm guessing if it is more efficient to always convert that id in integer even if it is an integer or to ask if it is an string and then convert it. I mean this:

let myArray = [{id: 1, ...otherprops}, {id: 2, ...otherprops}, {id: '3', ...otherprops}, {id: '4', ...otherprops}];

Is this more efficient ...

for (let x of myArray) {
   if (parseInt(x.id, 10) === 3) {
      ...
   }
}

Or this code:

for (let x of myArray) {
   let id = -1;
   if (typeof x.id === 'string') {
      id = parseInt(x.id, 10);
   }
   if (id === 3) { ... }
}

Since the first code always convert I don't know if two conditions are better.

2
  • @Bian Goole -- the parsing tag is not about conversion of strings to numeric types; please read about the intended uses of tags before adding them.... Commented Oct 19, 2017 at 13:19
  • @DavidBowling I appreciate your comment, it was the way I found to a quick solution. I reading now what you've suggested. Commented Oct 19, 2017 at 13:22

1 Answer 1

3

If you know, that you have just numbers or stringed numbers, then you could take an unary plus + for conversion to a number, which does not change numbers.

var id = +x.id;
Sign up to request clarification or add additional context in comments.

1 Comment

that's it, it solves the problem... I didn't know that... thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.