How do I flatten an array of arrays?

flatten array of objects javascript
flatten(array of arrays javascript)
flatten array of arrays python
array.flat is not a function
typescript flatten(array)
lodash flatten array of arrays
array-flat polyfill
flatten array php

I have an array consisting of following elements:

var schools = new [] {
    new object[]{ new[]{ "1","2" }, "3","4" },
    new object[]{ new[]{ "5","6" }, "7","8" },
    new object[]{ new[]{ "9","10","11" }, "12","13" }

The real object that i try to flatten is from importing data into array of arrays from CSV and then joining it on values of fields:

    var q =
        from c in list
        join p in vocatives on c.Line[name1].ToUpper() equals p.first_name.ToUpper() into ps
        from p in ps.DefaultIfEmpty()
        select new object[] { c.Line,  p == null ? "(No vocative)" : p.vocative, p == null ? "(No sex)" : }; 

I want to flatten that array of strings to get:

string[] {
    new string[]{ "1","2","3","4" },
    new string[]{ "5","6","7","8" },
    new string[]{ "9","10","11","12","13" }

I already have an solution that does that in loop, its not so performance-wise, but it seems to work ok.

I've tried to use SelectMany but cannot make up a solution.

Thank you very much for feedback ;) I've tried answer from npo:

var result = schools.Select(z => z.SelectMany(y=> y.GetType().IsArray 
           ? (object[])y : new object[] { y })

But CSVwriter class method accepts only explicitly typed:


So how to do it in linq, I've tried to:

List<string[]> listOflists = (List<string[]>)result;

But no go, InvalidCastException arrises, unfortunately.

In a first step, you have to normalize the data to one kind of type. Then you can iterate over them as you like. So at first create a method to flatten the values from a specific point to an arbitrary depth:

public static class Extensions
    public static IEnumerable<object> FlattenArrays(this IEnumerable source)
        foreach (var item in source)
            if (item is IEnumerable inner
                && !(item is string))
                foreach (var innerItem in inner.FlattenArrays())
                    yield return innerItem;

            yield return item;

Now you can either iterate on the top level to get a single array of all values:

// Produces one array => ["1", "2", "3", "4", ...]
var allFlat = schools.FlattenArrays().OfType<string>().ToArray();

Or you can create individual array one depth deeper:

foreach (var item in schools)
    // Produces an array for each top level e.g. ["5", "6", "7", "8"]
    var flat = item.FlattenArrays().OfType<string>().ToArray();

Merge/flatten an array of arrays, These are the three known ways to merge multidimensional array into a single array. Flatten Array using Array.flat () in JavaScript Setting depth parameter. By default, flat () will only flatten one layer deep. In other words, depth is 1. Deeper Nested Arrays. The great thing is that this method also works beyond 1 level deep. You simply have to set the Infinitely Nested

As per the comments, because your inner array mixes elements of string[] and string, it likely won't be trivial to do this directly in Linq.

However, with the assistance of a helper function (I've called Flattener) you can branch the handling of both of the inner types manually to either return the elements in the array (if it's string[]), or to return the single element as an enumerable, if it's not. SelectMany can then be used to flatten the inner level, but the outer level seemingly you want to leave unflattened:


var schools = new [] {
    new object[]{new[]{"1","2"}, "3","4"}, 
    new object[]{new[]{"5","6"}, "7","8"},
    new object[]{new[]{"9","10","11"}, "12","13"}

var result = schools
    .Select(s => s.SelectMany(o => Flattener(o)));

Which returns a type of IEnumerable<IEnumerable<string>>

Where the messy unpacking bit done by:

public IEnumerable<string> Flattener(object o)
    if (o is IEnumerable<string> strings)
        return strings;
    if (o is string s)
       return new[]{s};
    return new[]{"?"};

Note the above uses the pattern matching capabilities of C#7.

Result screenshot courtesy of LinqPad:

Flattening multidimensional Arrays in JavaScript, Flatten array of arrays with JavaScript. Tags javascript, node.js. const arrays = [[1]​, ["2"], [3]]; const merged = [].concat(arrays); console.log(merged); // [ 1, '2', 3 ]. To make sure you're only getting arrays of Person back, you can cast your array to be of type Person[]to give you an extra layer of type safety: const flattenedArray = ([] as Person[]).concat(nestedArrays); When to use this. For flattening arrays of arrays only one level deep! When not to use this

If you want o do it via linq here is a sample

     var schools = new[] {
    new object[]{new[]{"1","2"}, "3","4"},
    new object[]{new[]{"5","6"}, "7","8"},
    new object[]{new[]{"9","10","11"}, "12","13"}

var result = schools.Select(z => z.SelectMany(y=> y.GetType().IsArray ? (object[])y : new object[] { y }));

Flatten array of arrays with JavaScript, It was always complicated to flatten an array in #JavaScript. Not anymore! ES2019 introduced a new method that flattens arrays. And there's a  So Array.concat() join all nested array and create js flatten array. It also a good approach but it works if an array is one level nested. Spread Operator With Concat to Flatten Array. The spread operator is used to expand array and object which is help to Flattening Multidimensional Arrays in JavaScript. Now, look at the example below.

Flatten Array using Array.flat() in JavaScript - DailyJS, A practical guide to flattening JavaScript arrays. Published Dec 10, 2019. ES2019 introduced two new methods to the Array prototype: flat and flatMap . They are  We introduce the To1DArray method, which receives a 2D int array and returns a flattened form. The result is a 1D array—we will need to access its elements with an expression.Int Array 2D Array. Step 1: We access the 2D array's total element count—the Length property on a 2D returns this value. Step 2: We copy the 2D array elements into a 1D array. We loop over each dimension.

How to flatten an array in JavaScript, An overview of two new methods available on the Array prototype in JavaScript: flat and flatMap. The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.. The source for this interactive example is stored in a GitHub repository.

Flatten Arrays in Vanilla JavaScript with flat() and flatMap , [ 1, 2, 3, 4 ]. // Since 'flat' doesn't automatically detect the depth,. // we could use reduce & concat to go down recursively until the end. function flattenArray(arr) {. Get the Arrays in the form of 2D array. Create an empty list to collect the flattened elements. With the help of forEach loop, convert each elements of the array into stream and add it to the list Now convert this list into stream using stream () method.

  • Sounds like a homework problem.
  • Because you are mixing arrays of strings with strings I don't think there is going to be an easy linq solution. I think you'll need to do a more traditional loop checking if each item is an array or a string and dealing with it based on that check.
  • "I've tried to use SelectMany" Then show what you´ve tried please. I doubt it´ll help you if anyone here comes to the exact same solution you already have and posts it here.
  • One thing: I note in your examples that there is always one string array and it is always the first item in the object array. Is that a rule or is that just coincidence in your test data?
  • If this kind of structure is generated "naturally" by your application or data (i.e. not a puzzle or homework exercise), consider reworking it. While you can write code to process it (as the answers show) part of the difficulty is that this kind of structure is rather poorly typed as far as O-O is concerned. For example, if single strings were represented as one-element arrays, the whole thing would fit naturally in a string[][][]. Alternatively, proper classes that encapsulate the data that those strings represent would also help (string Value and string[] Children, for example).
  • Proof that just because it can be done in LINQ doesn't mean it has to be done in LINQ. Nicely figured out though.
  • Note that casting an array to object[] only works if the array is of reference type. int[] cannot be converted to object[]. A more general solution would be ... y=> y is IEnumerable ? ((IEnumerable)y).Cast<object>() : new object[] { y } However, be careful; string implements IEnumerable<char>, so you might want a test for string-ness in there!