Enhancing arrays with reduce function and map operation in Javascript

I am looking to reorganize the structure of an array.

For example, consider this array [col1,col2,col3,col4]

I want to nest the elements so that the first element becomes a separate array like this

[[col1], [col2,col3,col4]]

I attempted the code below, but it is placing col2 into the first array position

jsfiddle.net/0ht35rpb/57 - visualization of the issue

k['key'] = i
if (i % 2 === 0) {
 m.push([k])
} else {
 m[m.length - 1].push(k)
}
return m

This is my attempt:

function arrayMaker(menu) {
  var l = []
  menu.reduce((m, k, i) => {
    if (i === 0) {
      m.push([k])
    } else {
      l.push(k)
    }
    if (i === menu.length - 1) {
      m.push(l)
    }
    console.log("m", m)
    return m
  }, [])

}

var menu = ["col1", "col2", "col3", "col4"]
var nest = arrayMaker(menu)
console.log("nest", nest)


Here is the complete code block, presenting a seemingly complex solution for a simple problem.

    {
     lang.menu.reduce((m, k, i) => {
       m.push(k)
       if (i === lang.menu.length - 1) {
         m = [m.slice(0, 1), m.slice(1)]
       }
       return m
     }, []).map((grouped, index) => (
       <div key={index} className={index === 0 ? 'main-footer__left' : 'main-footer__right'}>
         {
           <div className='row grid__row--offset--30'>
             {
               grouped.map((item, j) =>
                 <div key={j} className={(index === 0 && j === 0 ? 'large-45 large-centered' : 'large-14 large-offset-5') + ' columns'}>
                   <h2 className='text--uppercase text--white footer-text'>{item.title}</h2>
                   {
                     item.switch
                       ? <p className='text--white grid__row--offset--15 footer-text'>
                         {
                           item.children.map(function (child, j) {
                             return (
                               <Link key={j} className={'text--white footer-text transition ' + (props.active_language === child.title.toString().toLowerCase() ? activeLang : alternativeLang)} to={urls[j]}>{child.title}</Link>
                             )
                           })
                         }
                       </p>
                       : item.children.map(function (child, j) {
                         return (
                           <div key={j} className={(j === 0 ? ' grid__row--offset--15' : '')}>
                             <Link className='text--white footer-text transition' to={child.link}>{child.title}</Link>
                           </div>
                         )
                       })
                   }
                 </div>
               )
             }
           </div>
         }
       </div>
      ))
    }

Answer №1

For creating a new array, one option is to utilize the Array#slice method along with the original array.

var array = [1, 2, 3, 4],
    result = [array.slice(0, 1), array.slice(1)];
    
console.log(result);

Answer №2

I have a sneaky trick up my sleeve:

var array = [1, 2, 3, 4],
   result = [[array.shift()], array];

console.log(result);

Answer №3

One more

let numbers=[5,6,7,8];
let sum=numbers.reduce((prev,current,index)=>((prev[index?1:0]=prev[index?1:0]||[]).push(current),prev),[]);

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

Webpack converts 'import' statements to 'require'

I'm currently in the process of compiling my nodeJS project using webpack. Everything seems to be working correctly after compilation, but I've noticed that the imports are being changed to requires. This causes an error when trying to run index. ...

How about starting a Node.js application with specific configurations?

Is there a way to develop a Node.js app that can be initiated with additional parameters? Here are a few examples: node myApp.js -nolog This command would initialize the app with the custom parameter noLog=true, preventing console logging. node myApp.js ...

Nested ng-repeat in AngularJS by numeric value

Looking to create a sliding carousel layout for displaying a bunch of data with 8 points per slide. The desired structure is as follows: Slide datapoint 1 datapoint 2 datapoint 3 datapoint 4 datapoint 5 datapoint 6 datapoint 7 ...

Guide to retrieving a specific cell value from a gridview and showcasing it in a textbox with jquery on an asp.net platform

Below is the code for my grid view. It consists of a column labeled "Syllabus" and the next column contains edit and delete buttons. When the Edit button is clicked, a popup appears using jQuery. The popup includes a textbox for the Syllabus. How can I ret ...

What is the most efficient way to eliminate div elements from the DOM tree individually?

Check out this example. If you click the add button, a user card is added. You can remove all cards by clicking the "Clear" button. But how can you delete individual cards by clicking the "close" icon on each one? Here's the HTML code: <div clas ...

Utilizing JavaScript to control the visibility of a div based on radio button selection without the need

I am facing an issue with my HTML code that is only partially working. I am attempting to display text inputs based on a radio button selection. At the moment, the code successfully hides the other options when a radio button is clicked, but upon the ini ...

Tips on utilizing jQuery or JavaScript to efficiently filter out outcomes exceeding a specified range

<input type="range" name="rangeInput" min="100000" max="750000" onchange="updateTextInput(this.value);"> Displayed above is the slider code that provides a value output below. <div id="sliderValue"> <p>Max Value £</p> <input t ...

How can I redirect to a different page with a keypress event in Next.js?

I am looking to implement a redirection function in nextjs when users press a key. There is a search input field where users can type and then hit the enter key to navigate to another page. Here's what I have attempted: const handleKeyPress = (e) = ...

Expanding and collapsing multiple tables in Material-UI

I'm currently working on creating a collapsible table using MaterialUI. At the moment, all my slides have collapses but they are connected to one state for "open", so when I open one slide, all the other slides also open. Here is an example sandbox t ...

Comparison between modules and standalone components

It has come to my attention that there is a growing trend in Angular 17 to move away from using modules, opting instead for standalone components. This approach makes Angular more similar to Vuejs or React, where the concept of modules is not as prominent. ...

Leveraging Server Response Codes Across Different Domains Using JavaScript

Before anything else, I must acknowledge the cross-domain issues that may arise with JavaScript. The fact that I am seeing both 404 and 200 response codes in my console has made me reconsider this possibility. The scenario... I am currently developing a w ...

Animation does not occur after the stop() function is executed

My goal is to create a functionality where, upon moving back to the grey content box after leaving the button, the slideUp animation stops and the content slides down again. This works seamlessly with jQuery 1.x (edge), but when I switch to jQuery 1.10, th ...

Browsing through items within arrays to evaluate their values

I am facing an issue with two arrays that consist of objects. The first array contains restaurant objects with attributes such as name and averagePrice, while the second array has price objects (cheap, medium, expensive) with properties like label, lowEnd, ...

Replicate and $(document).ready()

My form has required fields that need to be completed. To alert users about blank fields, I have implemented the following code: $(document).ready(function() { $('input.required:text').focus(function() { $(this).css({'background ...

Sending image to the server with the help of JavaScript

Curious if there is a method to upload an image to the server using javascript or jQuery and then save the image path/name into a database. I am working on a Windows platform server in asp.net 1.1, revamping a web page that is 10 years old. Unfortunately, ...

How can you access the URL of a resource action in Angular?

In my Angular application, I have created a resource named 'Files' with the following definition: app.factory('Files', function($resource) { return $resource('/api/accounts/:account_id/sites/:site_id/files/:file_id'); }); ...

Check to see if the variable is present in LocalStorage using Javascript

Currently working on a chat system where I create a Localstorage variable whenever a new chat is initiated. Here's how I do it: localStorage.setItem("chat_"+varemail, data); My next step is to figure out how many of these chat variables exist. Somet ...

The Elusive Solution: Why jQuery's .css() Method Fails

I am currently facing an issue with my code that utilizes the jQuery .css() method to modify the style of a specific DIV. Unfortunately, this approach does not work as expected. To illustrate the problem, I have provided a simplified version of my code bel ...

Utilizing a Frozen Tensorflow Model with NodeJS for High-Performance Computing

I am new to tensorflowjs and js in general, but I have a trained model that I need to run on it. I have converted the model to json format, but I am having trouble feeding data into it: const tf = require('@tensorflow/tfjs') const tfn = require( ...

CSS styling doesn't take effect until the page is reloaded due to the failure of cssText

After generating a new list item, it appears that the CSS styling is not being inherited until the page is reloaded. Even though I have added styling using cssText dynamically, it doesn't seem to be working as expected. I've attempted using cssT ...