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

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Create and adapt dynamic tiles to fit within the available width

I am looking to create a dynamic tile (div) that adjusts based on the number of users available, similar to how it works in Microsoft Teams meetings. For example, if there is only one user, the div should occupy the full screen. When there are two users ...

How to seamlessly integrate Redux into your React project using create-react-app?

Is it correct to pass a reducer as props when using a rootreducer? This is the content of my rootReducer.js file: import { combineReducers } from 'redux'; import simpleReducer from './simpleReducer'; import messageReducer from '. ...

Toggle Visibility of Div Based on Matching Class Name When Clicked

Just delving into the world of jQuery and could use some guidance. Is there a way to show a div with a matching class when a specific button is clicked? For example, clicking on a button with the class '.project1' should display the corresponding ...

Having trouble locating the module '.outputserver ode_modulespiniadistpinia' in Nuxt3 and Pinia?

I recently integrated Pinia into my Nuxt3 project, and while everything works fine in development mode, I encountered an error when trying to access the application in production mode resulting in the website freezing. [h3] [unhandled] H3Error: Cannot find ...

Issue encountered when attempting to invoke a PHP function using Javascript through AJAX

I'm currently working on incorporating a PHP function into my HTML file using Ajax (which also contains JavaScript). My goal is to retrieve all locally stored JSON files. I've been following a guide at , but I'm facing some challenges. When ...

Utilizing JQuery to make Google listings easily findable

Implementing Google Places for a location text box has been successful. However, I am now looking to create a class-based implementation so that I can use it with multiple places effortlessly. Is it possible to achieve this using JQuery? <script type ...

Is there a way to utilize two onChange functions within one component?

I'm having trouble utilizing two onChange functions within the same component. I attempted to combine them, but I ran into an issue because one is using useState and the other is a const function. Below is my code snippet: const signup = () => { ...

What could be the reason for TypeScript being unable to recognize my function?

In my code, I have a Listener set up within an onInit method: google.maps.event.addListener(this.map, 'click', function(event) { console.log(event.latLng); var lt = event.latLng.lat; var ln = event.latLng.lng; co ...

Leveraging python capabilities within html documents

English is not my first language, so please excuse any spelling errors. I am working on combining HTML and Python to develop a graphical user interface (GUI) that can communicate with a bus system (specifically KNX bus). Currently, I have a Raspberry Pi ...

A ReactJS Error occurred: {error: 400, reason: "Failed match", message: "Failed match [400]", errorType: "Meteor.Error"}

I encountered an issue while attempting to send form data to the server when clicking on the Next Button in a Wizard Form. The error that occurs is related to an "Undefined User" warning displayed in the Console during Step 1 of the form submission: " { ...

Managing value state with several Formik forms within a single component

I'm currently in the process of constructing a web page using React and Formik. Within this form page, I have integrated three distinct Formik forms that are conditionally displayed based on a switch statement. The reason behind structuring it this wa ...

Making a REST call with values containing an apostrophe

Currently, I am utilizing REST and ajax to retrieve data from SharePoint using the URL below: https:xxxxxxxx/_vti_bin/ListData.svc/RMSD_Tasks?$orderby=IssueValue asc,StatusValue desc&$filter="+dropValue+" eq '"+secondFilterVal+"'&groupby ...

How can I trigger a JavaScript function when the ENTER key is pressed?

I'm attempting to use JavaScript to scroll down a page. The code below works perfectly when I use javascript:pageScroll() in a link or button: <SCRIPT LANGUAGE="Javascript"> function pageScroll() { window.scrollBy(0,50); // hor ...

Tips for adding new items to a Masonry Image List using React MUI

As I experiment with utilizing the React MUI Masonry Image List alongside the infinite scroll, I've found that they complement each other quite well. However, a challenge arises when appending new images to the Masonry image list. While I can success ...

What is the optimal frequency for saving data when dealing with a particularly extensive form?

I am facing a challenge with saving data to the database using Ajax. While I can handle this aspect, my difficulty lies in the fact that I have a very extensive form that is nested and cannot be altered. This large form consists of approximately 100 input ...

Modify input value using jQuery upon moving to the next step

When you type into an input[text] and press the tab button, it automatically moves to the next input. If you fill out all the inputs and then want to re-fill them, the values will be highlighted in blue. However, I wanted to achieve this without having to ...

What is the best way to switch between light and dark themes with the ability to locally store the current theme?

Being new to the realm of react, I have been delving into the implementation of new features using Material-UI. One particular feature I am working on involves toggling between light and dark themes, with the current theme being stored locally within the b ...

Angularjs 2 Error: Unable to access the 'infos' property of an undefined object using the Http Client

I've been working on an AngularJS app for about a week now, developing a backoffice application for my service. My main challenge lies in using data retrieved from a remote server. I have 4 HTTP GET requests in my app - 2 of them fetching lists of us ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...