ECMAScript Proposal: Array.prototype. {Flat, flatMap}

    ECMAScript Innovations



    Hello readers Habr. I bring to your attention an interesting thing thatwill soon appearalready appeared in the ECMAScript standard. She is already availablenearlyin all browsers and all the functionality too. This innovation is just sugar-wrapper and it can be solved by your own means and I will show it to you too. But this sugar will allow us to write less code, because we love it so much. So, the basic functions are added to the array, in this case there are 2 of them, which will allow us to expand multi-level arrays into one or more nesting levels. Yes, yes, and all this as they say out of the box


    ECMAScript Proposal: Array.prototype. {Flat, flatMap}


    This Proposal was once known as Array.prototype.flat {ten, Map} . It has stage status34 of TC39 that is alreadyCandidateFinished . I think it is worth a little distraction and talk about this very TC39 and about the standards, who are familiar with can miss this retreat. so:


    JavaScript standards and how it is prepared.


    ECMAScript


    ECMAScript is a standard that is developed and maintained by ECMA International . It was adopted by the Ecma General Assembly in June 1997. And more specifically, ECMAScript is the ECMA-262 standard , which is called “ECMAScript Language Specification”. The standard was created based on the original version of JavaScript from Brendan Aich from Netscape and the JScript interpreter from Microsoft, but has evolved significantly since then.


    JavaScript is an implementation of the ECMAScript specification . This means that as the specification has new drafts or published editions, browser and framework developers like Node.js should consistently implement new functionality. To do this, make changes to the engines that these browsers and frameworks use to interpret and execute JavaScript code.


    Why do you need a specification? Different browsers use different JavaScript engines, for example, V8 in Chrome, SpiderMonkey in Firefox, and so on. When you write in JavaScript, you expect that all engines in all environments will parse and execute your code in exactly the same way. Without a standardized specification, any of these engines would be free to execute JavaScript as it pleases, this is obviously not very good.


    TC39


    The Ecma International Technical Committee 39 (aka TC39) is a committee of very smart people, it is associated with a group of participants, too, by the way, smart. They all get together in meetings of the committee about once every two months and discuss in advance prepared lists of issues.
    The task of TC39 is to support and update the previously mentioned ECMAScript specification, after discussion and consensus. These include language syntax, semantics, libraries, and related technologies on which the language is based.


    This process is defined by TC39. It all starts with a draft of the functional, expanding or changing the specification. Such drafts often come from the developer communities, or from the TC39 members themselves. If the proposal is worthy, the draft receives the status of the official offer.


    Then, on its way from idea to publication, the proposal goes through several specific stages. They are numbered from zero to four men programmers :


    [“Strawman”, “Proposal”, “Draft”, “Candidat”, “Finished”]

    Transition to any of the next stages requires the approval of TC39. If the proposal has reached stage 4, it can be expected to be included in the next officially published edition of the ECMA-262 specification specification, and as a result it will appear in the environment that executes JavaScript. You can learn more about this process from the document itself .


    All existing proposals for an introduction to the standard can be found here on github
    well, now let's go further ...


    Array.prototype.flat


    The flat () method returns a new array,


    var newArray = arr.flat(depth);

    in which all elements of nested arrays were recursively "raised" to the specified depth level .


    Example:


    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]

    There is also a side effect, it removes undefined elements of the array.


    Example:


    const arr4 = [1, 2, , 4, 5];
    arr4.flat(); //? [1, 2, 4, 5]

    Rubric do it yourself


    Use reduce and concat


    Example:


    const arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
    functionflattenDeep(arr1) {
       return arr1.reduce((acc, val) =>Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
    }
    flattenDeep(arr1); //? [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]

    Array.prototype.flatMap



    The flatMap () method first applies the function to each element, and then converts the result to a flat structure and places it in a new array. This is identical to the map function, followed by the use of the flat function with a depth parameter of 1, but the flatMap is often useful because it works a little more efficiently.


    var new_array = arr.flatMap(functioncallback(currentValue[, index[, array]]) {
        // return element for new_array
    }[, thisArg])

    callback - The function that produces the elements of the new array takes three arguments:


    1. currentValue - The current processed element of the array.
    2. index (optional) - The index of the item to be processed in the array.
    3. array (необязательный) — Массив по которому осуществляется обход.
      thisArg (необязательный) — Значение используемое в качестве this при вызове функции callback.
      Возвращаемое значение — Новый массив, каждый элемент которого является результатом выполнения функции callback и "поднят" на уровень 1.

    пример:


    [
        { x: 1, y: 2 }, 
        { x: 3, y: 4 }, 
        { x: 5, y: 6 }
    ].flatMap(c => [c.x, c.y])  //?  [1, 2, 3, 4, 5, 6]// orconst orders = [
        {
            orderId: 42,
            items: [
                {name: 'soap', price: 1.99},
                {name: 'shampoo', price: 4.99}
            ]
        },
        {
            orderId: 1337,
            items: [
                {name: 'toothpaste', price: 5.59},
                {name: 'toothbrush', price: 8.99}
            ]
        }
    ];
    orders.flatMap(i => i.items.map(i => i.name)); //? ["soap", "shampoo", "toothpaste", "toothbrush"]

    Рубрика делаем сами


    var arr1 = [1, 2, 3, 4];
    arr1.reduce((acc, x) => acc.concat([x * 2]), []);
    // [2, 4, 6, 8]

    Заключение


    Remember that this functionality is added to the language for a reason. The reasons why smart people from TC39 do it are improving the quality of language, abstraction, usability, and others. Examine these innovations in advance, and by the time they are officially published and will be maintained everywhere, you will be able to start working right away without losing time. You can also position yourself as a JavaScript expert in your organization, able to offer new language features to improve both the code and the product itself.


    ps: while the article was being written :), Proposal moved to stage 4
    Array.prototype.{flat,flatMap} to stage 4, per 2019.01.29 TC39


    Also popular now: