0

I am using the lastFM api with this plugin. https://github.com/fxb/javascript-last.fm-api

I have a for loop that calls the "makeList" function 3 times based on an array of lastfm users.

var makeList = function( num ) {
    // query using last fm api 
    // spits out an array of 3 objects
}

for ( var i = 0; i < 3; i ++ ){
   makeList( i );
}

My questions: 1) How can I consolidate these arrays into 1 array with 9 objects 2) Can I randomize the items in the array?

From console.log

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
cusejuice
  • 10,285
  • 26
  • 90
  • 145
  • 2
    [Concat](http://www.w3schools.com/jsref/jsref_concat_array.asp) and [Randomize](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) – NaNpx Nov 21 '13 at 20:00
  • 1
    @NaNpx You should put that in an answer. – eliot Nov 21 '13 at 20:37

1 Answers1

1

You can use array.concat to combine your arrays, and a custom sort function to randomize the order of the items in that array.

var arr1 = [
    { name: 'Alan' },
    { name: 'Barney' },
    { name: 'Cassius' }
];

var arr2 = [
    { name: 'Derek' },
    { name: 'Eric' },
    { name: 'Fred' }
];

var arr3 = [
    { name: 'Graham' },
    { name: 'Howard' },
    { name: 'Isaac' }
];

// Now I am one big array
var bigArray = arr1.concat(arr2, arr3);

// Now my member objects are randomized
bigArray.sort(function() {
    return 0.5 - Math.random();
});
Nate
  • 4,718
  • 2
  • 25
  • 26