2

I want to update all object child values with the same value, let's do it by code:

var days = [
   {
      title: 'Day 1',
      checked: false
   },
   {
      title: 'Day 2',
      checked: true
   },
   {
      title: 'Day 3',
      checked: false
   }
];

Now if I want to updates the property checked for all days array nodes, I do this:

$.each(days, function(i, day) {
   day[i].checked = true;
});

So, I'm looking for a better way for doing this, something like this:

days[*].checked = true;

Thanks in advance.

4
  • If the array has hundreds of nodes, I think the loop will be less performance, if I have to do this several times in my App. Commented Apr 18, 2015 at 6:49
  • 2
    In my opinion every technique has to iterate over your days .so you current approach is good Commented Apr 18, 2015 at 6:54
  • If you really eager to optimize performance: Helpful Article & Avoid $.each( ... ) Commented Apr 18, 2015 at 6:57
  • If you really care about performance, don't use jQuery for loop. Although it's micro optimization anyway. Commented Apr 18, 2015 at 6:58

1 Answer 1

4

As I've already mentioned comment below the Question! $.each( ... ) is very costly for the performance. Though it can be only detected at large amount of data in an Array!

And as per This Article : And this Question...

Most light-weight and easy to use way is While loop:

var len = arr.length;
while (len--) {
  arr[len] *= 2;
}

Then another preferable and more treditional is do-while loop:

var len = arr.length;
do {
  arr[len] *= 2;
} while (len--);

Least preferable is Array map :

arr.map(function(el) {
  return el * 2;
});

enter image description here

And there are many other ways to loop through array and are costly than above couple of methods.

After Edit:

Disadvantages of $.each() loop :

  1. Lower performance compare to other loops (for games/animations/large datasets)
  2. Less control over iterator (skip items, splice items from list, etc).
  3. Dependency on jQuery library unlike for, while etc loops!
  4. Not familiar syntax, as most other similar languages.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so the $.each is the worst way to loop through the array, may you give me the reason?
@LeoAref, Edited the answer and added main disadvantages of .each over other loops. Is the answer helpful?

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.