0

I'm adding new photos to my database in groups as they are uploaded to Instagram. Say my first call to the Instagram API returns 5 photo objects in an array, [20,21,22,23,24]. 20 being the most recent and 24 the oldest. Then my next call several minutes later returns 5 newer photo objects, [15,16,17,18,19]. 15 being the most recent and 19 the "oldest" (but always newer than 20), and on and on.

Ideally I would like my database to store the objects as [15,16,17,18,19,20,21,22,23,24] or [24,23,22,21,20,19,18,17,16,15]. However, if I use push I end up with: [20,21,22,23,24,15,16,17,18,19], while if I use unshift I end up with: [19,18,17,16,15,24,23,22,21,20,]

1 Answer 1

1

It looks like you need to reverse your original arrays.

Demo:

var x = [20, 21, 22, 23, 24];
var y = [15, 16, 17, 18, 19];
var pushed = [];
var unshifted = [];
var i;


for(i = 4; i >= 0; i--) {
    pushed.push(x[i]);
    unshifted.unshift(x[i]);
} 

for(i = 4; i >= 0; i--) {
    pushed.push(y[i]);
    unshifted.unshift(y[i]);
}

console.log(pushed); // outputs [24, 23, 22, 21, 20, 19, 18, 17, 16, 15]
console.log(unshifted); // outputs [15, 16, 17, 18, 19, 20, 21, 22, 23, 24]
Sign up to request clarification or add additional context in comments.

Comments

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.