Use the map function to find the highest number within each array

function each(collection, func) {
  if (Array.isArray(collection)) {
    for (var i = 0; i < collection.length; i++) {
      func(collection[i], i);
    }
  } else {
    for (var key in collection) {
      func(collection[key], key);
    }
  }
}

function map(array, func) {
  var result = [];
  each(array, function(element, i) {
    result.push(func(element, i));
  });
  return result;
}

function findMax(numbers) {
  var maximum = numbers[0];
  each(numbers,function(x){
    if(x>maximum){
      maximum = x;}
  });
  return maximum;
}

function maxNumbers(arrays){
  return map(arrays, function(x){
    return findMax(arrays);
  })
}

maxNumbers([1,2,3],[5,6,7])

I'm struggling to understand the concept of the map function. I successfully created a function to find the maximum number in an array using the each function, and now I'm trying to apply that to the map function. However, the return statement returns the same maximum number three times for each array, which I don't quite understand. I've tried different approaches like returning max(arrays[x]) but it didn't work as expected. Any help would be appreciated.

Answer №1

To find the maximum value in array x

function getMaximums(arrays) {
    return map(arrays, function (x) {
        return findMax(x);
        //         ^                         
    });
}

Then, call the function with an array of arrays

getMaximums([[1, 2, 3], [5, 6, 7]]);
//       ^                    ^

function each(collection, func) {
    if (Array.isArray(collection)) {
        for (var i = 0; i < collection.length; i++) {
            func(collection[i], i);
        }
    } else {
        for (var key in collection) {
            func(collection[key], key);
        }
    }
}

function map(array, func) {
    var result = [];
    each(array, function (element, i) {
        result.push(func(element, i));
    });
    return result;
}

function findMax(numbers) {
    var maximum = numbers[0];
    each(numbers, function (x) {
        if (x > maximum) {
            maximum = x;
        }
    });
    return maximum;
}

function getMaximums(arrays) {
    return map(arrays, function (x) {
        return findMax(x);
    })
}

console.log(getMaximums([[1, 2, 3], [5, 6, 7]]));

Answer №2

Using a better building block, reduce (also known as foldLeft), can significantly improve the structure of your code compared to relying on each. By breaking down functions into simpler components and utilizing higher-order functions, we can create more efficient and cleaner code.

  • Avoid using each which limits to side-affecting functions
  • No need to check for Array.isArray
  • Avoid imperative style for loops with mutable iterators
  • No necessity to check array .length property

It's recommended to step through the evaluation of this code to understand how each part functions. This will help in mastering fundamental concepts of functional programming such as recursion, immutability, referential transparency, higher-order functions, currying, and function composition

ES6 features such as arrow functions, destructuring assignment, and spread syntax simplify writing functional programs in JavaScript, albeit requiring some adjustment in reading. Below the ES6 snippet, you'll find an ES5 version for a more familiar syntax approach.

Related: What do multiple arrow functions mean in JavaScript?

Still need help?

While reduce is a crucial function in the programs above, an alternative approach using JavaScript's built-in Array.prototype.reduce can provide similar results with less complexity. Aligning our program's expectations through a small uncurry combinator can bridge the gap between binary and curried functions.

Mastery of these concepts is a solid foundation in functional programming


Extra credit 1

Besides map, reduce can serve as the foundation for various other functions like filter, find, some, every, keys, and entries.

Extra credit 2

Some functions mentioned in Extra Credit 1 exhibit short-circuit behavior where the final answer can be determined before iterating through the entire array. Identifying these functions and adapting reduce to facilitate early exit could enhance efficiency.

Answer №4

There is no need to create your own functions for these operations. Utilize Math.max along with Array#map as shown below:

function findMaximum (array) {
    return Math.max.apply(null, array)
}

console.log(
    [[1,2,3], [5,6,7]].map(findMaximum)
) //=> [3, 7]
    
// If you prefer a separate `findMaximums` function
function findMaximums (arrays) {
    return arrays.map(findMaximum)
}

console.log(
    findMaximums([[1,2,3], [5,6,7]])
) //=> [3, 7]

Answer №5

By utilizing both the map and reduce functions, you can achieve great results:

function findMaxValues(arr) {
    return arr.map(function(subArr){
        return subArr.reduce(function(prev, curr){ return Math.max(prev, curr); });
    });
}

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

Extract data from an ajax request in an AngularJS directive and send it to the controller

I am currently experimenting with integrating the jQuery fancy tree plugin with Angular. The source data for the tree is fetched through an ajax call within my controller. I am facing a challenge in passing this data to my directive in order to load the tr ...

Reactjs is experiencing issues with the data mapping function

Currently, I am developing with Reactjs and utilizing the nextjs framework. In my current project, I am working on fetching data from a specific URL (https://dummyjson.com/products) using the map function. However, I encountered an error message: TypeError ...

Simulating dynamic route parameters in the Next 13 application directory

I am currently working with Jest and testing library to conduct unit tests on my NextJS application. I am facing difficulties in rendering a page on a dynamic path. Here is the code for my page/component: export default async function MyPage({ params }: { ...

Difficulty encountered while implementing the if-else statement in raycasting operations

Currently, I am experimenting with raycasting to determine if my mouse is pointing at an object. The function seems to be working fine when the object is not being touched - it correctly prints out "didnt touch". However, when the object is touched, it s ...

Instructions for resolving the Sys.ArgumentTypeException error: The object of type 'Object' cannot be converted to type 'Function'

I encountered a specific error in my JavaScript function that I'm struggling to resolve. Uncaught Sys.ArgumentTypeException: Sys.ArgumentTypeException: Object of type 'Object' cannot be converted to type 'Function'. Parameter name ...

Unfulfilled promises are left hanging

I've encountered a problem while writing a unit test for my Angular application using Jasmine with a mock service. The promise I am trying to run is not functioning as expected. Below is the service code: CreateItemController = $controller('Cre ...

What are some javascript libraries that can be used to develop a mobile image gallery for both Android and iPhone

I currently have the touch gallery system in place, but unfortunately it isn't functioning properly on Android devices. ...

Develop a design utilizing a foundational database entity

I'm new to AngularJS and I am seeking guidance on how to properly separate the model from the controller. In my previous experience, I have always integrated models within the controllers. For example: angular.module("app").controller("customerContr ...

Discovering checkboxes in HTML using jQuery

Greetings! I have limited knowledge when it comes to using jQuery. I am currently facing an issue with the Checkbox attribute. Below, you will find the code snippet that I have mentioned: Code: $( this ).html() Output: <input name="cb_kot[]" class= ...

I keep encountering the following issue: "It seems that the file requested at /images/crown.png is not recognized as a valid image, as it was received as text/html; charset=utf-8."

I encountered an issue while utilizing Next.js. Here is the code snippet where the error occurred: import React from "react"; import { Container, Col, Row } from "react-bootstrap"; import Image from "next/image"; export defaul ...

Navigating to a randomly generated ID in Firestore using Vue - A Step-by-Step Guide

My app uses Firestore as a backend for posts. On the screen displaying all categories, when a new category is created it's added to the list. When a category is clicked, I use its id as a parameter to navigate to that specific category and show the po ...

When you drag down on mobile Safari on an iPad, touch events may cease to fire in HTML5

When I implement event listeners to handle touch events like touchmove and touchstart document.addEventListener("touchstart", function(event){ event.preventDefault(); document.getElementById("fpsCounter").innerHTML = "Touch ...

Accessing the SQL database using Cypress

I am attempting to establish a connection with an SQL database using Cypress following the guidelines provided in the NPM guide. I have ensured that all dependencies are installed as specified, however, when I run the following query: cy.sqlServer('S ...

jQuery functions smoothly on Firefox, but encountering issues on Chrome

While it may seem like a repetitive inquiry, I have thoroughly researched similar questions and have not found a suitable solution. The server is returning the following response through a standard ajax call: <form id="ctl00" name="ctl00" method="post ...

Can you provide guidance on achieving a gradient effect throughout the mesh, similar to the one shown in the example?

Check out my code snippet on JSFiddle: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/215/ https://i.sstatic.net/r8Vxh.png I'm trying to achieve the appearance of the red/green box with the border style of the purple box. The purple box was created ...

Removing a value from an array using Jquery when an item is deselected from a dropdown

I'm currently facing a challenge in my project where I need to remove values from an array when they are unselected from a multi-select dropdown list. Adding values using push() works fine for me, but removing deselected values is proving to be more d ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...

Including v-menu in a button causes it to vanish in Vuetify

I am facing an issue with my stepper. Specifically, in step 3, I am trying to add a v-menu to a button but when I do so, the button disappears. Below is the code snippet causing the problem: <template> . . . . <v-stepper-step :complete="e6 > ...

Issue with JQuery: Inability to deactivate an element after receiving an Ajax response

My dynamic dialogue box, generated via Ajax return, presents a challenge involving the dynamically changing drop-down list element $('#functionSelect'). I require this list to trigger disabling of input fields within the dialogue box upon changes ...

Material UI offers a feature that allows for the grouping and auto-completion sorting

I am currently utilizing Material UI Autocomplete along with React to create a grouped autocomplete dropdown feature. Here is the dataset: let top100Films = [ { title: "The Shawshank Redemption", genre: "thriller" }, { title: " ...