SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict ketting00's Avatar
    Join Date
    Jul 2011
    Posts
    325
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)

    How do I chop off arrays and rearrange them to a new one

    I've this kind of arrays that generated from other function:
    Code:
    [[0], [0,0,0,0]]
    [[1], [1,1,1,1]]
    [[2], [2,2,2,2]]
    [[3], [3,3,3,3]]
    I want to rearrange it to:
    Code:
    [[0,0,0,0], [1,1,1,1], [2,2,2,2], [3,3,3,3]]
    or better yet:
    Code:
    [0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3]
    How could I do this.
    This is my experiment so far and it's still far from working:
    Code:
    var a = [[0], [0,0,0,0]];
    var b = [[1], [1,1,1,1]];
    var c = [[2], [2,2,2,2]];
    var d = [[3], [3,3,3,3]];
    
    var e = [];
    var f = [];
    var g = [];
    var h = [];
    
    function x(data) {
    	switch(data[0].toString()) {
    		case '0':
    			e = data[1];
    			break;
    		case '1':
    			f = data[1];
    			break;
    		case '2':
    			g = data[1];
    			break;
    		case '3':
    			h = data[1];
    			break;
    	}
    	var i = e.concat(f, g, h);
    	console.log(i); // [0, 0, 0, 0]
    					// [0, 0, 0, 0, 1, 1, 1, 1]
    					// [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2]
    					// [0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3]
    }
    
    x(a);
    x(b);
    x(c);
    x(d);
    I want only the last result of the var i, provided that data sent is in the above order.
    Thank you,

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,834
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Possibly like this?

    Code:
    var a = [[0], [0,0,0,0]];
    var b = [[1], [1,1,1,1]];
    var c = [[2], [2,2,2,2]];
    var d = [[3], [3,3,3,3]];
    
    var e = a.concat(b,c,d);
    var f = e.reduce(function(a, b) {return a.concat(b);});
    console.log(f);
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Addict ketting00's Avatar
    Join Date
    Jul 2011
    Posts
    325
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Hi felgall,

    Thank you. You're a superman.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •