-2

I want to get numbers from

var arr = [1,[2],[[3]],[[[4]]]];

using JavaScript/jQuery.

could be more in the series.

7
  • 2
    use Array.prototype.reduce() Commented Apr 11, 2017 at 17:33
  • That is a horrible explanation of what you want to accomplish and doesn't identify any format for expected results. Please take the time to read How to Ask. Also please show what you have tried...this isn't a free code writing service Commented Apr 11, 2017 at 17:36
  • Granted, the question is poor, but it's not a dup of the article linked by @Brian. Commented Apr 11, 2017 at 17:38
  • @YuryTarabanko very similar, but different. A multidimensional array is more complex than an array of arrays (n=2). The answer accepted there will not flatten the n=4 dim array from hemant, it needs more recursion Commented Apr 11, 2017 at 17:41
  • You forgot to show us all the code that you wrote and explain specifically what's not working with it. Commented Apr 11, 2017 at 17:48

2 Answers 2

0

You are looking for Array.prototype.reduce()

For example:

var arr = [1,[2],[[3]],[[[4]]]];

const flatten = arr => arr.reduce(
  (acc, val) => acc.concat(
    Array.isArray(val) ? flatten(val) : val
  ),
  []
);

console.log(flatten(arr));

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

2 Comments

it is good, i did not know this function (flatten) but neither I know ECMAScript 6. Can you please explain me this in ECMAScript 5?
@Hermant without the use of ES6 fat arrow functions, the code would be: const flatten = function(arr) { return arr.reduce( function(acc, val) { return acc.concat( Array.isArray(val) ? flatten(val) : val ); }, [] ); };
0

Realistically, if you only want to get the numbers you can just convert the array to a string then use a simple regex to extract all of the numbers:

console.log([1,[2],[[3]],[[[4]]]].toString().match(/\d+/g)); // ["1","2","3","4"]

If the result must be an array of numbers (not strings), you can use Array#map to run the conversion (e => +e).

console.log([1,[2],[[3]],[[[4]]]].toString().match(/\d+/g).map(e => +e)); // [1,2,3,4]

7 Comments

great solution, but critical assumption that strings are ok
@john edited to include example that returns numbers instead of strings.
Again, very good solution, but still has a restricted use case. You can't flatten a multidiminsional array of objects using a .match() approach, for example. If OP has your use case, yours is ideal, but a truly generic flatten needs something like Array.prototype.reduce()
@John Of course, if they are looking for anything other than just the numbers, then a recursive flattening will need to happen. As I said in the first sentence of my answer, this is only applicable if they only want to get the numbers.
Not really understanding the downvote here.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.