Best method for unifying Array<Array<T> | T> in JavaScript

I am working on developing a function that can handle an array containing arrays, literals, or even objects and flatten it into a one-dimensional array. An example of valid input would be [5, [2, 3], 7, [9, 0, 1]], which should produce the output [5, 2, 3, 7, 9, 0, 1].

Here is my current code for achieving this task. While it works fine, I am looking to optimize it further for efficiency while ensuring compatibility with ES5.

function flattenArray(list) {
  var result = [];
  for (var index = 0; index < list.length; index++) {
    result.push(list[index] instanceof Array ? list[index] : [list[index]]);
  }
  return [].concat.apply([], result);
}

console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));

Answer №1

Have you considered using the Array.flat method?

function flattenArray(list) {
  return list.flat()
}

console.log(flattenArray([5, [2, 3], 7, [9, 0, 1]]));

This approach appears to be the second fastest option (according to the linked performance test) and is compatible with ES5.

console.log([].concat.apply([],[5, [2, 3], 7, [9, 0, 1]]))

Performance test

Answer №2

When it comes to your code: It is unnecessary to put single elements into arrays, as using .concat will handle them properly. For example:

[1].concat([2], 2)

This code works just fine without needing to wrap 2 in [2]. This simplifies your code to just one line.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips on changing the name of a property within an object using JavaScript

While this question may appear to be a duplicate, there is actually a distinction. I am attempting to provide a new key that does not contain any spaces. {order_id :"123" , order_name : "bags" , pkg_no : "00123#"} My goal is ...

Is it possible to delay the execution of the code until the ajax function has completed

After executing the fillContent function, I need to call beginEditingQuestion. fillContent(cid, "questions"); beginEditingQuestion(qid); The issue is that beginEditingQuestion can't be executed until all the ajax requests in fillContent are complete ...

How to hide an ASP.net panel with JavaScript

I am working on a radioButtonList that contains two items: one with a value of "Yes" and the other with a value of "No." Below the radioButtonList, I have a panel that I would like to show when the "Yes" radiobutton is selected, and hide when the "No" rad ...

The function of jQuery .click() not triggering on elements within msDropDown

I'm having difficulty implementing jQuery on an Adobe Business Catalyst site. The HTML snippet below shows the structure: <div class="banner-main"> <div class="banner-top"> <section class="banner"> <div class="catProd ...

Is there a method to apply the background-color of the parent element based on the child class in CSS?

Is there a method to change the parent's background color based on the child's class using CSS? Here is the sample code snippet: Sample Code If the child has a class of red, the parent should have a red background. If the child has a class of ye ...

Tips for effectively utilizing foreach loops in JQuery

I've encountered an issue while displaying a list of data in a table using Smarty templates and foreach loops. I'm trying to make each line clickable to show new data below it, but currently, this functionality only works for the first line. Is t ...

Tips on preventing a lone track in Laravel for Server Sent Events

In my Laravel app, I am exploring the use of Server Sent Events. The issue I have encountered is that SSE requires specifying a single URL, like this: var evtSource = new EventSource("sse.php"); However, I want to send events from various parts/controlle ...

I'm experiencing an issue where the video won't play on my mobile device when I

Why won't my html5 video play on mobile when I tap it? It works fine on desktop, but not on mobile. When I tap the video, it should start playing, but that's not happening. This is the code I'm using: $(document).on('mouseover', ...

Using vue.js to compute properties for each object element

Vue.component ('app-mansion', { data: function () { return { message: 'Greetings, world', mansions: [ {name: "SKY8"}, {name: "SKY12"} ...

Issue: [next-auth]: `useSession` function should be enclosed within a <SessionProvider /> tag in order to work properly

Encountering an error loading my ProfilePage where the page loads fine in the browser but an error appears in the terminal. Error: [next-auth]: `useSession` must be wrapped in a <SessionProvider /> All child components are properly wrapped using Se ...

What is the process for finding an array in Algolia?

I have been struggling to find a solution to my problem. Here is a sample array from my database: { Users:{ { "name":"User1", "interest":["cats"] }, { "name":"User2", "interest":["dogs"] }, { "name":"User3", " ...

Obtain eligibility by determining the attribute value of an array object

I am trying to calculate the total qualifications based on a specific attribute value (idInteraction). How can I efficiently iterate through the array? My current approach is to iterate based on abilityOrder, but I'm having trouble matching it with i ...

What is the best way to test an oclif CLI tool that interacts with a Rest API

How can I efficiently test the TypeScript code I've written for an Oclif CLI that interacts with a Node.js and Express.js REST API? I'm currently using Mocha/Chai for testing, but I'm struggling with testing the specific command code from my ...

Issue with toggleClass not functioning properly after receiving data from an AJAX call

On my website, I have a link that triggers an AJAX request. However, when the response comes back and I try to use the toggleClass function in the following .js code snippet, it doesn't work as expected: $(document).ready(function(){ $("td").click( ...

Tips for hiding a child element by setting its display property to none while the parent element is set to block

My current setup involves a Bootstrap Jumbotron that wraps a Bootstrap list. The Jumbotrom is hidden by default: <div class="jumbotron" id="shoppingCart" style="display: none"> <h1 class="display-4" >Checkout</h1> <p class="lead" ...

What is the final symbol in a char array in C++?

I currently have a 'char' array that ends with the symbol '\0'. #include<iostream> void main() { char letters[4]; letters[0] = 'r'; letters[1] = 'r'; letters[2] = 'r'; lett ...

Can a variable be integrated into ng-repeat?

Just starting out with angular and had a question - can the firstP element inside the ng-repeat Directive be replaced with a variable? Currently working with AngularJS v1.6.6 ng-repeat="option in people['firstP']" var people = { "firstP": ...

I'm feeling uncertain about the installation process of Nodejs

I recently updated to the newest version of node, 20.10.0, so I can begin working with React. What should I do with the previous version? Is it safe to delete it or is it better to keep it? If I decide to remove it, could that impact any existing files t ...

Choose an image to be displayed at either full width or full height, depending on which dimension is reached first

I have a query regarding resizing an image within a div to either 100% width or 100% height of the containing div. Despite setting max-height and max-width to 100% as recommended here, I still encounter overflow issues without wanting to crop the image usi ...

Modifying the input field value in React

I've been attempting to modify the value of an input field after selecting an item from the SelectField in the MaterialUI library. Despite my efforts, I have not yet succeeded. However, based on my research, everything I have written appears to be cor ...