convert array of arrays to array javascript code example

Example 1: javascript array flatten

// flat(depth), 
// depth is optional: how deep a nested array structure 
//		should be flattened.
//		default value of depth is 1 

const arr1 = [1, 2, [3, 4]];
arr1.flat(); 
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 2: js convert array of arrays to array

// Converts array with multiple values into a single array with all items:
var merged = [].concat.apply([], arrays);

Example 3: convert array to array

new_images = array();
// format image before upload
for ($i = 0; $i < count($images['name']); $i++) {
  $new_images[] = array(
    'name' 		=> $images['name'][$i],
    'type' 		=> $images['type'][$i],
    'tmp_name' 	=> $images['tmp_name'][$i],
    'error' 	=> $images['error'][$i],
    'size' 		=> $images['size'][$i],
  );
}

<pre>Array
(
    [name] => Array  (
            [0] => Screen Shot 2020-10-21 at 10.44.30 AM.png
            [1] => Screen Shot 2020-10-21 at 9.56.12 AM.png )
    [type] => Array (
            [0] => image/png
            [1] => image/png )
    [tmp_name] => Array   (
            [0] => /Applications/MAMP/tmp/php/phpnlVcZU
            [1] => /Applications/MAMP/tmp/php/php1qaHkj  )
    [error] => Array (
            [0] => 0
            [1] => 0 )
    [size] => Array  (
            [0] => 61923
            [1] => 62194)

)
</pre>

// to 
<pre>Array
(
    [0] => Array (
            [name] => Screen Shot 2020-10-21 at 10.44.30 AM.png
            [type] => image/png
            [tmp_name] => /Applications/MAMP/tmp/php/phpJz6xqI
            [error] => 0
            [size] => 61923 )
    [1] => Array  (
            [name] => Screen Shot 2020-10-21 at 9.56.12 AM.png
            [type] => image/png
            [tmp_name] => /Applications/MAMP/tmp/php/phpHSBXaI
            [error] => 0
            [size] => 62194  )
)
</pre>

Tags:

Php Example