Is there a way to concatenate arrays without using the Array.flat method?

I am encountering an issue with a specific function that I have

const flat = function(arr, n) {
  if (n == 0) {
    return arr;
  } else if (n == 1) {
    let newarr = []
    for (let i = 0; i < arr.length; i++) {
      if (Number.isInteger(arr[i])) {
        newarr.push(arr[i])
      } else if (Array.isArray(arr[i])) {
        newarr.concat(arr[i]) //look here
      } 
    }
    return newarr
  }
};

console.log(flat([2,4,[2,4,9],1,6],1))

that is, when the function is called with these values

([2,4,[2,4,9],1,6],1)

The expected output should be

2,4,2,4,9,1,6

however, the actual output is

2,4,1,6

This means that the array inside another array is not being included in the final result

Answer №1

When using Array.concat, a new array is returned. To avoid reassigning the array or use spread operator for better results.

newarr.push(...arr[i])

Update

I agree with @mplingjan's suggestion. Using Array.flat can be beneficial in this scenario.

const flat = function (arr, n) {
    if (n == 0) {
        return arr;
    } else if (n == 1) {
        let newarr = []
        for (let i = 0; i < arr.length; i++) {
            newarr.push(...Array.of(arr[i]).flat())             
        }
        return newarr
    }
};

Answer №2

Another approach could be to implement it using recursion.

newarr.push(...flattenArray(arr[i]))

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

"Exploring the Functionality of Page Scrolling with

Utilizing Codeigniter / PHP along with this Bootstrap template. The template comes with a feature that allows for page scrolling on the homepage. I have a header.php template set up to display the main navigation across all pages. This is the code for th ...

declaration of function interface and property that cannot be modified

After reviewing some new TypeScript code, I encountered a part that left me puzzled. interface test { (a: number): number; readonly b: number; } While I understand that (a:number): number signifies a function where the argument is a:number and the ret ...

Every other attempt at an Ajax request seems to be successful

I'm new to using ajax and I'm having an issue with submitting a form through a post request. Strangely, the code I wrote only works every other time. The first time I submit the form, it goes through ajax successfully. However, on the second subm ...

Adding an Ajax response to a div in HTML: A step-by-step guide

How can I add Ajax response to a div in my HTML code? Below is my ajax script: $(document).ready(function(){ $('.credit,.debit').change(function(){ var value=$(this).val(); $.ajax({ type:"POST", url:" ...

Protection of Angular expressions

I have been following the PhoneCat tutorial for AngularJS and found it very helpful up until step 6 where links are generated dynamically from angular expressions: http://localhost:8000/app/{{phone.imageUrl}} Although the tutorial mentions that ngSrc pre ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

Quantities with decimal points and units can be either negative or positive

I need a specialized input field that only accepts negative or positive values with decimals, followed by predefined units stored in an array. Examples of accepted values include: var inputValue = "150px"; <---- This could be anything (from the input) ...

Retrieving values with Jquery on a function's onClick event

Here is a small script that retrieves values from a select element <script> jQuery(document).ready(function() { var selectedValue = jQuery("#tr_val").val(); }); </script> When you click on this div and execute the open_win function, I need t ...

While loop not yielding immediate result with asynchronous function

As a beginner in Node.js, I have successfully connected an LCD Panel and a 4x4 Membrane matrix keypad to my Raspberry Pi. Using Node.js, I have programmed them to work together. My goal is to have the LCD panel immediately display any key pressed on the ke ...

Customize your Angular UI Bootstrap Datepicker with unique buttons - here's how!

Currently, I have a datepicker with clear and close buttons. I tried using the append function to add more buttons to this datepicker, but it didn't work because the content is not loaded until we click the icon since it's a popup datepicker. Is ...

The absence of the 'Access-Control-Allow-Origin' CORS header was noticed in the response from the Wikipedia API

Attempting to retrieve data from the Wikipedia API using axios in reactJS. Here is my request: axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?') .then((response) => { c ...

Resize an image to fit perfectly within a material-ui grid

Is there a way to resize images within a grid layout without them getting cropped? Each image I try to fit into the top horizontal grid behaves differently due to varying dimensions. Instead of stretching and fitting into the container, the images end up b ...

Issue with sending data to the server via API using AngularJS controller

I am a beginner in angular js and I am attempting to POST data to the server using an API that I have created: function addmovie_post() { { $genre = $this->post('genre'); $cast = $this->post('cast'); $director ...

Identifying when a user has inputted incorrect $routeparams

How can I restrict user input to only "id" as a query parameter in the URL? $scope.$on('$routeUpdate', function () { var id = $routeParams.id //check if user has entered any params other than "id". //if yes do someting }); I want ...

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

Sending both an array and an image via Ajax in a single request

I need to send both JSON and file data to my PHP backend using an ajax call. Here is my current ajax call: $.ajax({ type: 'POST', dataType: 'json', data: jsonData, url: 'xxx.php', cache: false, suc ...

Converting JSON to a list using JavaScript

As a beginner in JavaScript, I apologize for asking possibly a redundant question. Can someone guide me on the most effective way to parse json? I am specifically interested in extracting a list of strings under the name Maktg: { "d":{ "res ...

What are some ways to adjust the size of the option field in a select menu?

In my ionic popup, I have a HTML property called select with nested options. Below is the code snippet along with the applied CSS. My query is how can I set the white space to occupy the entire area of the select? https://i.stack.imgur.com/iPqAa.png http ...

The autocomplete feature in Atom is not functioning as expected

Autocomplete+ is included with the installation of Atom and is activated by default. I have noticed that when I am coding, no suggestions are appearing. What could be causing this issue? Do I need to adjust any files in order for Autocomplete+ to functio ...

Utilizing Mootools to Access and Obtain the Current Query String Parameters

Is there a way to extract the current querystring values using mootools? I have implemented mootools ajax for php pagination. The initial call includes the following parameters: format=html&nolayout=true&p[0]=1000-1500&p[1]=1500-2000&p[2] ...