"Can someone help me figure out how to retrieve a smaller array? I can't seem to get

I need help reducing an array.

My desired output should be [1,5,4], but unfortunately I am getting back an empty array.

let arr=[1,[2,3],4]
let newarr=[]
 
let myarr=()=>{
    for(i=0;i<3;i++){
        array=arr[i].reduce
        newarr.push(array)
        return newarr
    }
}

Answer №1

To successfully utilize array.reduce, you must pass a function to it and then actually execute the function, like shown below (where console.log is used to call it):

const arr = [1, [2, 3], 4];

const myArr = (arr) => {
  let newArray = [];
  arr.forEach((arrayItem) => {
    // Iterate through each item in the array
    if (Array.isArray(arrayItem)) {
      // Check if the item is an array that needs reduction
      newArray.push(
        arrayItem.reduce(function (previous, current) {
          return previous + current;
        })
      ); // Reduce array to a single value using a reducer function and add it to new array
    } else {
      newArray.push(arrayItem); // If not an array, push it as is to the new array
    }
  });
  return newArray;
};

console.log( myArr(arr) );

There are always more concise and elegant ways to achieve the same result. The solution above aims for readability, but a one-liner alternative would be:

const arr = [1, [2, 3], 4]
const newArr = arr.map(i=>Array.isArray(i)?i.reduce((a,b)=>a+b):i)
console.log(newArr)

Answer №2

Array#reduce is a method specific to arrays that requires a function to be passed as an argument. You've defined a function, but have not invoked it.

To fix this issue, you can try the following:

let arr = [1, [2, 3], 4];
let newarr = [];
 
((array) => {
    for(let i=0; i < array.length; i++) {
        const el = array[i];
        const topush = Array.isArray(el) ? el.reduce((total, curr) => total + curr, 0) : el;
        newarr.push(topush)
    }
})( arr );

console.log( newarr );

Alternatively, you can achieve the same result using both Array#map and Array#reduce. The key in both cases is to identify when to apply the reduce method on the array elements:

const arr = [1, [2, 3], 4, [4, 5, 7]];

const newarr = arr.map(el => 
    Array.isArray(el) ? el.reduce((sum,cur) => sum + cur, 0) : el
);

console.log( newarr );

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

Save the current state of the collapsible navigation menu

I developed a website for a friend, but I'm encountering an issue with my js/css vertical and collapsible menu. Every time I click a link, the new page loads and the entire menu collapses again. I've tried to figure out a way to "store" the infor ...

Please anticipate the completion of data loading

I need help adding a custom tweet button to my Angular application. Below is the code I am using: HTML: <a href="" class="retweet" retweet target="_blank" data-info="{{ data.name }}"> Tweet </a> JS: myApp.directive('retweet', ...

Search functionality that dynamically updates results as the user types, thanks

I am currently working on implementing a search feature that can assist users when typing in their search queries. The goal is to use Ajax to dynamically show results as the user types. Currently, the functionality requires the user to hit the search butt ...

Ways to create loops in Excel without using macros

Sorry for repeating the question, but I am unable to comment due to lack of reputation. I am faced with a similar query as How to loop in excel without VBA or macros?, however, I need to explore recursive loops in Excel without macros for a slightly differ ...

What is the encoding for Javascript in UTF-8?

My current ajax call is able to successfully send the request and retrieve the expected response. However, I am facing difficulty in correctly displaying it in li items. $.ajax({ url: "{% url 'users:profile_page_tags_get' 'primary&apos ...

Tips for eliminating redundancy in $scope manipulation code within multiple controllers using angularJS

Apologies if this question seems trivial, but I am just getting started with angularJS. I have created two controllers: seekerController and wizardController... Within the wizardController, there is a Scope object called chat, which is being manipulated ...

Issue with PHP retrieving initial value of post data

Hi there, I am facing an issue with my PHP code where the first value of the input field is not being displayed. However, when I check the console.log, it shows correctly. Here is my console.log output: https://i.sstatic.net/eZvg6.png PHP Output: https ...

In JavaScript, efficiently remove specific node types from a tree structure using recursion, while also maintaining and distributing qualified child nodes

Currently, I am working on a recursive function that operates on a JSON tree structure {name, type, [children]}, with the goal of removing nodes of a specific type. However, it is essential that the children of the removed node are reattached to the parent ...

PHP: A guide to traversing a multi-dimensional array and printing out the arrays within it rather than the individual elements within those arrays

Usually when I search, I find what I need, but this time I'm a bit lost. I decided to create a multidimensional array using the following approach: Below is the code - from input to push: This is the text entered into the textarea: VIE-CAI HA ...

Modify a single element within an array of objects stored in MongoDB

My collection of documents includes: { _id: ObjectId('111111111111111111114444'), books: [ { id: ObjectId('111111111111111111113333'), pictures: [] }, { id: ObjectId('111111111111111111112222' ...

The MongoClient object does not possess the 'open' method

I recently started working on a project using Node.js, Express.js, and MongoDB. I've encountered some issues while trying to set up the database configuration. Below is a snippet of code from my index.js file: var http = require('http'), ...

React - modifying parent's Redux property

After connecting my Container to redux using the following: const mapStateToProps = ({ MyReducer }) => ({ myProp: MyReducer.myProp }); I am wondering if it is possible to manually set the value of myProp from the parent component (bypassing redux) ...

Modify the templateUrl in routeProvider according to the user's authorization

Is there a way to dynamically change the templateUrl in the router provider based on user permissions? Here's an example of what I'd like to achieve: $routeProvider .when('/',{ if(user) templateUrl:'app/views/pages/h ...

Regenerate main JavaScript files in Gulp whenever partials are edited

In my gulp task for javascript files, I included partial js files in the source and filtered them out to avoid building them unnecessarily. gulp.task("js", () => { return gulp .src([ src_js_folder + "*.js", src_js_f ...

Saving JSON data as a file on server

Currently, I am running a localhost website on my Raspberry Pi using Apache and I am seeking advice on how to export a JSON string to a file on the Raspberry Pi itself. While I do know how to export a file, I am unsure of how to send it to the Raspberry Pi ...

What is the best way to test speedy AJAX response times using Webdriver.io?

Currently, I am creating Cucumber.js tests using Webdriver.io. Everything seems to be going smoothly, but I'm encountering an issue with the mock server responding too quickly with AJAX. The "Loading..." message is not visible because the content load ...

Exploring an Array within a Function in Ruby

Hello, I am new to using Ruby. I'm currently working on a program that takes user input, compares it with numbers in an array, and if there's a match, adds it to another number passed to the function. Here's what I have so far: numbers = [1 ...

Tips for comparing array objects in two separate React states

Comparing object arrays in two different React states can be challenging. Here is an example of the state values: review1 = [{name: John, Title: Manager},{name: Peter, Title: Engineer}, {name: Serena, Title: Supervisor}] review2 = [{personName: John, isma ...

Conceal Bootstrap 3 Modal and AngularJS navigation using $location.path

In my AngularJS App, I am utilizing the Bootstrap 3 modal as a dialog confirmation. However, when I hide the modal and redirect, the backdrop of the modal still remains visible. $scope.delete = function () { DataService.delete() .then(function () ...

Execute the gulp module on the source files

Recently, I've been delving into the world of gulp and trying to enhance the readability of my js source files. I have a task in place (which executes successfully) that utilizes 'gulp-beautify' to beautify the js files: gulp.task('js& ...