I have a 2D array in my code, but let's imagine we have a 3D array with dimensions [x][y][z]. How can I find the minimum and maximum values for the elements in the zth slice (where 0 < n < z) without the use of

var people = [
  ["Joe", 27, "US"],
  ["Mark", 34, "UK"],
  ["Alex", 22, "PK"]
];
document.write(people[1][1]);

If faced with a Multidimensional array, is it possible to determine the minimum and maximum values for [][][n] where 0 < n < z, without relying on Loops?

Answer №1

If you're facing a complex problem, my suggestion would be to break it down into two simpler parts:

  1. First, gather all values from the inner arrays (z) into a single list using flatMap
  2. Next, determine the minimum and maximum values within this resulting list

flatMap offers various implementations, with potential plans to introduce flattening as a standard array feature in browsers.

If the "no loops" constraint is a strict requirement, we can explore alternative solutions later on. For now, here's an initial approach to implementing flatMap for 3D arrays using reduce, concat, and map.

const flatMap = (f, xs) => xs.reduce(
  (acc, ys) => acc.concat(ys.map(zs => f(zs))),
  []
);

By calling this function with a method that retrieves a particular element n from each zs array, you can obtain a list of those elements.

flatMap(zs => zs[1], [ /* .... */ ]); // returns all elements at index `n` in the third dimension

Subsequently, applying Math.min and Math.max operations becomes convenient through spreading or reducing:

const minAge = Math.min(...flatMap(zs => zs[1], [ /* ... */ ]));

In a simulated scenario:

const data = [
  [
    ["Joe", 27, "US"],
    ["Mark", 34, "UK"]
  ],
  [
    ["Alex", 22, "PK"]
  ]
];

const flatMap = (f, xs) => xs.reduce(
  (acc, ys) => acc.concat(ys.map(f)),
  []
);

// Utilities
const max = xs => Math.max(...xs);
const min = xs => Math.min(...xs);
const pluck = k => o => o[k];

const minN = n => d => min(flatMap(pluck(n), d));
const maxN = n => d => max(flatMap(pluck(n), d));

const minAge = minN(1);
const maxAge = maxN(1);

console.log(
  "Minimum age:", minAge(data),
  "Maximum age:", maxAge(data)
)

If you are truly adamant about avoiding loops, recursion might be the only viable alternative. While reimagining flatMap recursively may not result in elegant code, let me know if you wish to delve into that territory.

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

Issue with Initializing MongoDB Database

Attempting to start a MongoDB database server is resulting in an error where the server fails to start. To address this, I have executed the mkdir -p data/db command in the project directory. The command I am running is: mongod --dbpath=data/ --port 27017 ...

Incorporate a new style into several previous slides using the Slick carousel feature

I'm attempting to utilize the Slick carousel to create a timeline. My goal is for the previous slides to remain colored as you progress through the timeline, and turn grey when you go back. I've tried using onAfterChange and onBeforeChange, but I ...

Is there a way to incorporate an event into the legend of chart.js?

I've recently managed to incorporate an event based on this post, but unfortunately, it's not being triggered. Any thoughts on why that might be? For reference, I am utilizing the default chart.js legend. Chart.helpers.each(vm.chart.legend.legen ...

"Combining the power of Angularjs and the state

I've been delving into Redux, mainly in the context of using it with React. However, I use AngularJS. Is there a compelling advantage to implementing Redux instead of handling state within AngularJS scope and letting Angular manage the bindings? ...

Deleting an argument from a recursive function

Hey there! I was given a task to create a method that generates all possible combinations of a given String input. For example: If the input is ABC, the method should return [A, AB, BC, ABC, AC, B, C] If the input is ABCD, it should return [A, AB, BC, CD, ...

What is the best approach to modifying array elements using onChange and hooks in React?

I'm struggling to implement something simple, and the solutions I've found so far don't quite address my specific issue. Here's the state in question: const [formFields, setFormFields ] = useState({ formTitle: '', fiel ...

Tips for implementing a jQuery mouseleave function for multiple div elements sharing the same id

I am facing an issue with my website where multiple divs share the same id. I need to implement a mouseleave function for all of these divs that have this specific id. Within my $(document).ready function, I currently have the following code... $('#m ...

Counting characters in a string and categorizing them into groups (lowercase and uppercase) in the C programming language

I created a C program that prompts the user for a string (with a 50-character limit) and separates the upper-case characters into a string called upper and the lower-case characters into a string called lower. The program is designed to print both of these ...

Issue with VueJS where the data list cannot be accessed from one template in another template

I'm facing an issue with my setup where there is a crash occurring on the v-for construct of the table-component. The error message displayed is: "Property or method "tablesList" is not defined on the instance but referenced during render". Strangely, ...

Region Covered by Mouse Over Does Not Extend Across Whole Div

On my website, there is an arrow located on the middle right side that, when hovered over with the mouse, reveals a sidebar. Clicking on each icon in the sidebar further extends it to reveal more content. However, the issue I am facing is that the sidebar ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Using AngularJS to Identify Parent-Child Nodes in JSON Data

I am in need of a JSON parsing guide that allows me to navigate through questions and locate child questions based on the Yes section. I have been unable to find any resources specifically addressing how to check for child nodes in JSON, with Angular being ...

It is impossible to choose a specific value within my client form and designate it as selected using Silvio Moreto's selectpicker

Can you assist me? I am currently working on a client CRUD system in PHP, JS, and AJAX, but I have hit a roadblock. The issue lies in the client edit form. When I click on "edit client," all the data for that client is successfully loaded into the form, e ...

The type does not contain a property named `sort`

"The error message 'Property sort does not exist on type (and then shoes4men | shoes4women | shoes4kids)' pops up when attempting to use category.sort(). I find it puzzling since I can successfully work with count and add a thousand separato ...

Best Practices for Angular Directive Controllers

When defining a directive controller, there are two main approaches outlined below for consideration: Option 1: angular.module('app')directive('AppHeader', AppHeader); function AppHeader() { var headerDirective = { restrict: & ...

"The issue with Node/Express BodyParser is that it is not correctly retrieving the data from input fields, resulting in either empty values

I am facing an issue with my basic express set up. Despite following tutorials, I am unable to capture the data entered by a user in two inputs; a text input and a dropdown input. Here is how my app.js file is structured: var express = require('expr ...

React - The ._id received by the Modal inside the map function is incorrect

My map is generating edit and delete buttons. The delete button requires confirmation, so I implemented a modal. When I use console.log(additive._id) on the first delete button, I get the correct ._id, but when I click the confirm button inside the modal, ...

Enhance your 3D model with a striking border using Three.js

Hello everyone, I am looking to create an outline on my 3D model using React Three Fiber. Has anyone successfully set this up before? const ModelStl = () => { const geom = useLoader(STLLoader, pathModelStl); const ref = useRef(); const { camera } ...

Can someone please provide me with a Javascript code snippet that accomplishes the same function

<script> document.addEventListener('DOMContentLoaded', function () { const menuItems = document.querySelectorAll('.headmenu li'); menuItems.forEach(function (menuItem) { menuItem.addEventL ...

Guide on filling in credentials in Facebook popup using Webdriver with Javascript

On my website, I have a feature where users can authenticate using Facebook. Currently, my site is not public, but you can see a similar process in action at agar.io. Just click on "Login and play" and then click on "Sign in with Facebook". This will open ...