How does one update an array's indices after using $.each

48 views Asked by At

I am using jQuery's $.each function to append (then delete) each item as I iterate through an array. I then use an if statement to stop iterating after deleting 8 objects. Here is a very simple example:

$.each(media, function(index, item) {
    if (index < 8) {
        $list.append(item);
        delete media[index];
    } else {
        return false
    }
});

The problem is if I run the code a second time, it runs eight times...but appends nothing. Here is a screenshot of from Chrome's console after the second run:

enter image description here

It appears as if this quirk has something to do with the fact that my indices don't re-sort/set after each time $.each is used. Am I missing something or is anyone aware of an elegant workaround for this?

3

There are 3 answers

0
philz On

Use the shift function?

var media = [1,2,3,4,5,6,7,8, 9, 10];
var $list = [];
for (var i = 0; i < 8; i++) {
    $list.push(media.shift ());
}

or

var media = [1,2,3,4,5,6,7,8, 9, 10];
var $list = [];

$.each(media, function(index, item) {
    if (index < 8) {
        $list.push(media.shift());
    } else {
        return false
    }
});

returns the same thing

console.log(media) = [9, 10]
console.log($list) = [1, 2, 3, 4, 5, 6, 7, 8]
0
guest271314 On

delete replaces item from array with undefined ; try utilizing Array.prototype.splice()

var i = 0;

do {
  var j = media.splice(0, 1);
  $list.append(j);
  ++i;
} while (i < 8);

var media = "abcdefghijklmnopqrstuvwxyx".split("");

var $list = $("span:first");
var _media = $("span:last");

var i = 0;

do {
  var j = media.splice(0, 1);
  $list.append(j);
  ++i;
} while (i < 8);

_media.append(media);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
list: <span></span><br />
media: <span></span>

0
Darpa On
var media_8= media.slice(0,8)
media= media.slice(8,media.length-8)
media_8.forEach(function(item) {
    $list.append(item);
});