0

I'm trying to make a kind of newswire for a school project but I'm having a few problems with jQuery's .each() function. I'm trying to find a way to skip every 2nd array element in a loop.

Basically I have data from a NY Times API and got both title and abstract and push these into an array that I then loop and animate every once and awhile.

My problem is, I can't seem to find a way to get Title + Abstract (Index[0]+[1]) without the loop just moving to index[1] again. Now I knows in Javascript you can simply use a for (i=0; i < array.length; i+2) and thus skip every 2nd array element, but I haven't had any luck incorporating that. Any suggestions? :)

$(document).ready(function() {
var newsWire = [];
    function loadNewswire() {
        return $.getJSON('http://api.nytimes.com/svc/news/v3/content/all/all.json',
        {'api-key': 'XXXXXXXXXXXXXXXXXXX'},
        function(data) {
            console.log(data)
            var newsWireTemp = [];
            for (var i = 0; i < data.results.length; i++) {
                var breakingNews = data.results[i];
                var breakingTitle = breakingNews.title.toUpperCase();
                var breakingAbstract = breakingNews.abstract;
                newsWireTemp.push(breakingTitle);
                newsWireTemp.push(breakingAbstract);
            }
            newsWire = newsWireTemp;
        });
    }
    loadNewswire().done(function () {
        var items = newsWire;
        $text = $('#newswiretxt span'),
        delay = 10; //seconds
        function loop (delay) {
            $.each(items, function (i, elm){
                $text.delay(delay*1E3).fadeOut();
                $text.queue(function(){
                    $text.html(items[i]+ ": " +items[i+1]);
                    $text.dequeue();
                });
                $text.fadeIn();
                $text.queue(function(){
                    if (i == items.length -1) {
                        loop(delay);   
                    }
                $text.dequeue();
                });
            });
        }
        console.log(items.length);
        loop(delay);
        });
});
DinoMyte
  • 8,737
  • 1
  • 19
  • 26
  • Well, it appears as though you have full control over how the data are pushed into the array... why not just push your `breakingNews` item into the array? Then you wouldn't have to worry about incrementing the index in an odd way... – Heretic Monkey Nov 12 '15 at 18:25
  • _"can't seem to find a way to get Title + Abstract (Index[0]+[1]) without the loop just moving to index[1] again"_ Is `$text.html(items[i]+ ": " +items[i+1]);` portion where `[i + 1]` should be set ? What is expected result if `items[i+1]` is `undefined` ? – guest271314 Nov 12 '15 at 18:26

6 Answers6

0

See if this SO thread helps you.

From what I understand, you'd like to skip every other iteration, so checking i's parity to skip when appropriate should work.

For the lazy:

$.each(array, function(index, item) {
    if(index % 2 === 0) return true; // This would skip
    // Other logic
});

Let me know if it helps or not.

Community
  • 1
  • 1
Dan Balaban
  • 735
  • 8
  • 10
0

Basically, just push the desired text concatenated into the array for the load function. Then as you iterate you can simply write the contents as is without messing with the iteration.

$(document).ready(function() {
   var newsWire = [];
function loadNewswire() {
    return $.getJSON('http://api.nytimes.com/svc/news/v3/content/all/all.json',
    {'api-key': 'XXXXXXXXXXXXXXXXXXX'},
    function(data) {
        console.log(data)
        var newsWireTemp = [];
        for (var i = 0; i < data.results.length; i++) {
            var breakingNews = data.results[i];
            var breakingTitle = breakingNews.title.toUpperCase();
            var breakingAbstract = breakingNews.abstract;
            newsWireTemp.push(breakingTitle + ': ' + breakingAbstract);
        }
        newsWire = newsWireTemp;
    });
}
loadNewswire().done(function () {
    var items = newsWire;
    $text = $('#newswiretxt span'),
    delay = 10; //seconds
    function loop (delay) {
        $.each(items, function (i, elm){
            $text.delay(delay*1E3).fadeOut();
            $text.queue(function(){
                $text.html(items[i]);
                $text.dequeue();
            });
            $text.fadeIn();
            $text.queue(function(){
                if (i == items.length -1) {
                    loop(delay);   
                }
            $text.dequeue();
            });
        });
    }
    console.log(items.length);
    loop(delay);
    });
 });
John Helfert
  • 182
  • 2
  • 12
0

Instead of using two array indexes, use one object, var bn={};, add the two entries, bn.breakingTitle=breakingNews.title.toUpperCase(); and bn.breakingAbstract=breakingNews.abstract; then one push newsWireTemp.push(bn); so each entry in newsWire is more like newsWire[i].breakingTitle and newsWire[i].breakingAbstract.

Alderin
  • 150
  • 1
  • 8
0

One way to do it:

Fiddle: http://jsfiddle.net/q18dv4wr/

HTML:

<div id="test1">odds:</div>
<div id="test2">evens:</div>

JS:

var someData = [0,1,2,3,4,5,6,7,8,9,10];
var div1 = $('#test1');
var div2 = $('#test2');
$.each(someData,
    function (index, value) {
        if (index % 2 == 0) {
            return;
        }
        else {
            div1.append(' ' + value);
        }
    }
);
$.each(someData,
    function (index, value) {
        if (index % 2 != 0) {
            return;
        }
        else {
            div2.append(' ' + value);
        }
    }
);

EDIT: Seems I posted a moment too late. Someone else gave same idea already. =] Oh well.

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43
0

You could do this: $text.html(items[i]+ ": " +items[(i+=1)]); But personally, I would push the breakingNews object into the array instead of having a different index for each property:

$(document).ready(function() {
var newsWire = [];
    function loadNewswire() {
        return $.getJSON('http://api.nytimes.com/svc/news/v3/content/all/all.json',
        {'api-key': 'XXXXXXXXXXXXXXXXXXX'},
        function(data) {
            console.log(data)
            var newsWireTemp = [];
            for (var i = 0; i < data.results.length; i++) {
                newsWireTemp.push(data.results[i]);
            }
            newsWire = newsWireTemp;
        });
    }
    loadNewswire().done(function () {
        var items = newsWire;
        $text = $('#newswiretxt span'),
        delay = 10; //seconds
        function loop (delay) {
            $.each(items, function (i, elm){
                $text.delay(delay*1E3).fadeOut();
                $text.queue(function(){
                    $text.html(items[i].title.toUpperCase()+ ": " +items[i].abstract);
                    $text.dequeue();
                });
                $text.fadeIn();
                $text.queue(function(){
                    if (i == items.length -1) {
                        loop(delay);   
                    }
                $text.dequeue();
                });
            });
        }
        console.log(items.length);
        loop(delay);
        });
});
Divide100
  • 224
  • 1
  • 2
  • 11
0

Try using .append() , checking if items[i + 1] is defined before appending items[i + 1] , else return empty string

$text.append(items[i] + (!!items[i+1] ?  ":" + items[i+1] + " ": ""))

var items = "abcdefg".split("")

$.each(items, function(i, item) {
  $("body").append(items[i] + (!!items[i+1] ?  ":" + items[i+1] + " ": ""))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
guest271314
  • 1
  • 15
  • 104
  • 177