1

I would like to flat nested arrays submited by users.

This is how it supposted to work: User put in input: [[1],[2],[3, 4],[5],[6, 7]] and he gets a result: [1,2,3,4,5,6,7]

It doesn't work because I can create an Array from input data.

$( document ).ready(function() {

//Get input data and make an array of it
var tablica = $('.tablica').val();
var myArray = [ tablica ];



$('input').on('click', function(e) {
e.preventDefault();

 console.log(myArray);
//myArray gives me: ["[[1],[2],[3, 4],[5],[6, 7]]"] instead of [[1],[2],[3, 4],[5],[6, 7]] and that's why script doesnt work..

var flat_arr = [].concat.apply([], myArray);



$('.wynik').html(tablica + ' => ' + flat_arr);


});  

});

HTML:

 <form>
  <input type="text" class="tablica" name="tablica" value="[1],[2],[3, 4],[5],[6, 7]">
  <input type="submit" value="Konwertuj">
</form> 

<p class="wynik"></p>

How I can make this script working? Don't know how to put properly input data into an array.

5 Answers 5

2

I would use JSON.parse then concat like so:

$( document ).ready(function() {

  //Get input data and make an array of it
  var tablica = $('.tablica').val();
  var temp = JSON.parse('['+tablica+']');
  var myArray=[].concat.apply([], temp);

  $('input').on('click', function(e) {
    e.preventDefault();

    console.log(myArray);

    $('.wynik').html(tablica + ' => ' + JSON.stringify(myArray));

  });  

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form>
  <input type="text" class="tablica" name="tablica" value="[1],[2],[3, 4],[5],[6, 7]">
  <input type="submit" value="Konwertuj">
</form> 

<p class="wynik"></p>

Sign up to request clarification or add additional context in comments.

2 Comments

Yep it's working, but I would like to get output in array so: [1,2,3,4,5,6,7]. How I can do it properly? I tried var flattered = [ flat_arr ] but result is still displayed like it's not an array. Displaying like this: "[" + flat_arr + "]" its not the best idea, because it's fake array then..
myArray is an array, to print it to the screen as an array you would need to so something like '['+flat_arr+']' or JSON.stringify(myArray), but again keep in mind that the var myArray is still an array
1

just try split and join to get the concatenated array

[[1],[2],[3, 4],[5],[6, 7]].join(",").split(","); //output [1,2,3,4,5,6,7]

//myArray gives me: ["[[1],[2],[3, 4],[5],[6, 7]]"] instead of [[1],[2],[3, 4],[5],[6, 7]] and that's why script doesnt work..

you need to do

var tablica = "[" + $('.tablica').val() + "]";
var myArray = JSON.parse( tablica ); //output [[1],[2],[3, 4],[5],[6, 7]]

1 Comment

This is neat, but not where Michal asked for? split and join will always turn it into 1 array with all the values
0

Your input is not an array, is a string. You can't put this string variable inside an array and expect magic to happen, but you can:

function strToFlatArray(s) {
  return s.replace(/[[\]\s]/g, '').split(',');
}


document.write(strToFlatArray('[1],[2],[3, 4],[5],[6, 7]'));

Or if you know you're going to get numbers, you might as well do:

function strToFlatArray(s) {
  return s.match(/\d+/g);
}


document.write(strToFlatArray('[1],[2],[3, 4],[5],[6, 7]'));

both of which return flat arrays.

Comments

-1

The issue is that tablica is not an array. its a string. You to call JSON.parse(tablica) to turn it into an array prior to manipulating it.

Comments

-1

gurvinder372's answer is a nice, quick and dirty approach that will work on some pretty deeply nested arrays. Just want to add on that this approach will turn numbers in to strings. To get them back to number form, add a map method on the end.

[[1],[2],[3, 4],[5],[6, 7]].join(",").split(",").map(x => Number(x));
// You could also just wrap 'x' in parens and force js to evaluate it.
// This saves you from writing that pesky Number constructor

Another, more comprehensive way to approach this is recursively

function collapse(array) {
  array.forEach(function(el, i) {
    if (Array.isArray(el)) {
      array.splice(i, 1);
      el.forEach(function(x) {
        array.push(x);
      });
      return collapse(array);
    }
  });
  return array;
};

This only ever hits the top level of the array, and checks if it contains child arrays. If so, it splices them out of the original, and pushes it's children into it's place. Arrays can be endlessly deep, but will not find arrays nested in objects.

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.