Only compress the initial layer of the array

I put in a lot of effort to create my own flatten function using functional programming. I have everything working smoothly except for some reason, false is not being included in the result. When I try to use it as an answer on codewars, it works for all scenarios except this one:

flatten([[[1,2,3]]]) // => [[1,2,3]]

Instead, my code is producing:

flatten([[[1,2,3]]]) // => [1,2,3]

What's frustrating is that I believe my output makes more sense than the expected one. However, regardless, I still want to resolve this issue. The problem lies in the fact that the structure I've created is quite complex, making it challenging to make modifications without disrupting everything and needing to refactor the entire codebase. I would like to create a specific function to handle cases like the one above but I'm unsure how to do so without causing disruption to the current setup. Any ideas on how to approach this?

All the other discussions related to this topic seem to focus on numpy, nothing relevant to JavaScript. Help, please!

Here's the code snippet:

var flatten = function (parentArray) {
return reduce(pushArray,[],parentArray);
}

function reduce(combine, base, array) {
  forEach(array, function(element) {
    base = combine(base,element);
  });
  return base;
}

function pushArray(baseArray,tempArray) {
  while (tempArray[0]) {
  baseArray.push(tempArray.shift()); }
return baseArray;
}

Answer №1

Just a quick note, I found this interesting:

If we assume that the forEach function looks something like this:

function forEach(arr, fn) {
  for (var i=0, iLen=arr.length; i<iLen; i++) {
    if (arr.hasOwnProperty(i)) {
      fn(arr[i], i, arr);
    }
  }
}

then:

flatten([[[1,2,3]]]) // => [[1,2,3]]

This seems to match your expectations. Did I interpret it correctly?

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

"Utilizing JSON.parse() to convert a string captured from a PythonShell back

Using PythonShell in Node to execute a Python script that generates a Python dict, such as: { "playedStatus": game['playedStatus'].encode('ascii'), "awayTeamAbb": game['awayTeamAbb'].encode('ascii'), "homeTeamAbb": ...

Having trouble figuring out what is causing non-serializable error in Redux (Redux error)

Initially, my react-native application was functioning smoothly and this particular page (screen) had been developed and working perfectly. However, out of the blue, it has started to encounter an error related to non-serializable data in the 'save_re ...

Eliminate HTML nodes that are not currently visible

I am currently developing a Vue/Vuetify application that showcases a large number of images (10-20k) in a grid view along with some additional information. These images are grouped into different sections, and clicking on an image opens an overlay displayi ...

Angular 2 with a jssor slider that adjusts seamlessly to different screen

After following the guidance provided in this answer on incorporating jssor into angular2, I have implemented the following JavaScript code snippet in a file and referenced it in angular-cli.json. jssor_1_slider_init = function() { var jssor_1_op ...

Swapping the icon in the panel heading of Bootstrap 3 Collapse based on its collapse status

Despite many attempts, I haven't been able to make any of the provided answers work in my code. My setup involves using Bootstrap 3 panels and collapse functionality to display advertisements. In the default view, only the advertisement heading is vi ...

What steps should I follow to ensure that the message "Read It" is logged to the console before "Ex It"?

app.get('/', async (req, res) => { await fs.readFile('./views/website/index.html', 'utf8', (err, d) => { data = d console.log("Successfully read the file") // console.log(data) ...

Obtaining only a portion of the text when copying and editing it

I have a React application where I am attempting to copy text from an HTML element, modify it, and then send it back to the user. I have been successful in achieving this, but I am facing an issue where even if I select only a portion of the text, I still ...

Fixed navigation menu at the top of the screen

Can anyone help me with my navbar issue? I want it to stay on top of the page, but there's a huge gap between the top of the page and the nav bar. I've tried running a JS file, but it doesn't seem to fix the problem. Any ideas on how to make ...

Tips for making sure there is a delay in between each axios call in a React

Currently in the process of developing an application that needs to interact with a RestAPI by sending a specific set of inputs. However, the API has a major flaw when it comes to scalability and tends to respond with code 429 if bombarded with too many re ...

Encountering an issue while attempting to implement Redux Toolkit alongside the MUI ToggleButtonGroup component

The error message initially started as: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. When I attempted to update the Redux state using a dispatcher, the handleChange function suddenly showed an e ...

The scrolling action triggered by el.scrollIntoViewIfNeeded() goes way past the top boundary

el.scrollIntoViewIfNeeded() function is used to scroll to element el if it's not within the visible browser area. Although it generally works well, I have encountered some issues when trying to use it with a fixed header. I have provided an example s ...

Extract data from dynamically loaded tables using PhantomJS and Selenium Webdriver

I've been informed by everyone that I should be able to retrieve the table content using PhantomJS when working with JavaScript. However, despite my attempts, I have not been successful. My expectation was to obtain the table from the website Page 1 ...

Incorporating additional text following the creation of an image composite using HTML5

I am facing an issue with positioning two images on a canvas using HTML5. Despite changing the x and y properties, the images remain stuck at the top left corner (0, 0). This is different from how I can position text easily on the canvas. <canvas width ...

Unable to show message upon form submission with ajax

I'm attempting to use AJAX to submit a form in CodeIgniter. The form values are being saved in the database, but the response set in the controller isn't displaying in the console.log or alert within the AJAX code. Form Code <form class=" ...

Stopping a NodeJs file running on an Ubuntu server

After enlisting help to install a Js script on my server, I encountered an issue where changes I made to the scripts/files were not reflected in the browser. After scouring the internet for answers for about 24 hours, I discovered that Js scripts need to b ...

"Enhance Your Website with Dynamic List Item Animations in

Working on a simple animation involves removing classes from list items once they are loaded and added to the document. However, I am encountering issues with the animation execution. I aim for a stepped animation pattern as depicted below... https://i.ss ...

Unable to execute Javascript function within a click event handler

I am encountering an issue with a div that is loaded through ajax. Here is the structure of the div: <div id="container"> <a href="#" class="easyui-linkbutton submit_data">Click here to submit</a> </div> Within the same file c ...

Exporting Blender model to three.js CanvasRenderer results in strange distortion of normals

I'm currently experiencing an issue while trying to export a model using the Three.js import/export tool for Blender. Everything works perfectly fine when I use the WebGLRenderer, but when I switch to CanvasRenderer for cross-browser support, the mode ...

Guide on triggering a bootstrap popup modal using a TypeScript file

I am currently working on an Angular project where I need to launch a popup modal when my function is called. I came across an example on w3schools, but it only contains the HTML logic to open the popup. What I want to achieve is to open the popup from th ...

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...