A guide on accessing array elements through conditions utilizing the reduce method in Javascript arrays

I'm working with an array of records:

const records = [
{
    value: 24,
    gender: "BOYS"
},
{
    value: 42,
    gender: "BOYS"
},
{
    value: 85,
    gender: "GIRLS"
},
{
    value: 12,
    gender: "GIRLS"
},
{
    value: 10,
    gender: "BOYS"
}

I need assistance in using JavaScript's reduce() method to extract only the objects with the gender "Boys" from this array, instead of using filter(). Can someone please help me with this?

Answer №1

Feel free to choose any option that suits you

const data = [{value: 24,gender: "BOYS"},{value: 42,gender: "BOYS"},{value: 85,gender: "GIRLS"},{value: 12,gender: "GIRLS"},{value: 10,gender: "BOYS"}]

const resultReduce = data.reduce((acc, item) => item.gender === "BOYS" ? [...acc, item] : acc, []);
const resultFlatMap = data.flatMap(item => item.gender === "BOYS" ? item : []);
const resultFilter = data.filter(({ gender }) => gender === "BOYS");

console.log(resultReduce);
console.log(resultFlatMap);
console.log(resultFilter);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Answer №2

const data = [
{
    number: 24,
    category: "MEN"
},
{
    number: 42,
    category: "MEN"
},
{
    number: 85,
    category: "WOMEN"
},
{
    number: 12,
    category: "WOMEN"
},
{
    number: 10,
    category: "MEN"
}

]

let men = data.reduce((total, obj)=>{
  if(obj.category === "MEN") total.push(obj)
  return total
},[])
console.log(men)

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

What is the method for executing a nested query in the Parse API?

Within the user object, there is a list of features: skills: {"piano:10", "singing:5", ....}; I am looking to filter users based on their 'piano' skills. How can I achieve this? It doesn't have to be an exact match but should follow the ru ...

The selected image should change its border color, while clicking on another image within the same div should deselect the previous image

https://i.sstatic.net/jp2VF.png I could really use some assistance! I've been working on Angular8 and I came across an image that shows how all the div elements are being selected when clicking on an image. Instead of just removing the border effect f ...

The website's responsive design functions flawlessly when viewed on a desktop browser or mobile-simulator for Safari and Mozilla Firefox. However, when accessed on an actual smartphone using Android or iOS

I've been experimenting with different lines of code, but I'm struggling to pinpoint the error as my code functions on a desktop and should also work on mobile devices... <meta name="viewport" content="width=device-width, initial-scale=1, max ...

What is the process for forming an array of pointers?

I need some guidance on creating an array of pointers that will reference a Student object I have designed. Can someone please explain how to accomplish this? Currently, my code looks like this: Student * studentPtr = new Student[5]; However, the issue ...

Assign the value from a drop-down menu to an SQL variable dynamically without the need for a submit button

I am trying to retrieve the value of the selected item in a drop-down menu populated from an SQL database. This value is essential for me to formulate the SQL statement required to access a specific record. The drop-down menu has already been populated. S ...

"What is the best way to use JavaScript to dynamically modify the hover color of a button

I am looking to customize the hover color of all buttons on my website to align with the overall theme. The challenge is that I need the hover color to vary based on the page it originates from. I have successfully identified the referring page, but I am s ...

Can the ajaxsetup error handler be used with the POST method?

I have a strange question - does the global error handler applied when using ajaxsetup get triggered in case of an Ajax error on a POST request? I've tried handling Ajax errors in several places, but the error handler is only being hit for GET reques ...

Increasing C# counter when instantiating a new object using an Array

Currently, I am creating objects within the Console class using an array: string[] console_available = { "Yes", "Yes", "Yes", "Yes", "Yes" }; for (int i = 0; i < console_available.Length; i++) { Classes.Console console = new Classes.Console(console_ava ...

Vue.js's @click feature can be enhanced with ternary operations

I've been attempting to achieve the following in Vue.js, but I keep encountering an error that says [plugin:vite:vue] Unexpected token (1:27): @click="selectedFiles.push(file.id); selectedFiles.length < 1 ? isCollapse=false: isCollapse=true&q ...

Issue with mobile.changePage() function not executing as expected

I created a basic code that generates a "Splash screen". For storing my data, I am utilizing localstorage. When I first load it, I retrieve data from a URL and I am able to navigate to different pages using $.mobile.changePage(). However, if the data is a ...

Techniques for eliminating text enclosed by double parentheses in javascript

I am currently working on extracting data from Wikipedia, but I am facing a challenge with removing content enclosed in multiple parentheses. While I can successfully remove single parentheses using content.replace(/\s*\(.*?\)\s*/g, &ap ...

Encountering errors like "Cannot find element #app" and "TypeError: Cannot read property 'matched' of undefined" typically happens when using vue-router

Recently, I decided to dive into Vue.js as a way to revamp an existing frontend app that was originally built using Scala Play. My goal is to explore the world of component-based web design and enhance my skills in this area. Initially, everything seemed ...

Retrieve data from one array using information from another array. Alternatively, merging the arrays could also be a solution

Welcome, developers, hackers, and watchers! I'm facing an issue that I can't quite wrap my head around, specifically the part where I need to extract data from one array based on another. Would merging them help? Let's take a look at the ...

Substitute the code in the data-ui-options attribute with a new chart code

I am new to this and I want to learn how to replace the chart code with the attribute data-ui-options using JQUERY. <div id="graficoHell" data-ui-jp="echarts" data-ui-options="{ xAxis: { data: ['a', 'b', &apo ...

Trading keys between arrays in JavaScript

I have a set of simple objects contained within an array: var myObject1 = [ {name: "value1", adddress: "545454545445"}, {name: "value2", adddress: "323233223"}, {name: "value3", adddress: "332 ...

Difficulty Showing Leading Digit on JavaScript Timepiece

Recently, I've been dabbling in creating a basic stopwatch script using JavaScript to showcase the elapsed seconds, minutes, and hours. The desired time format is: hh:mm:ss In my quest to achieve this with JavaScript, I encountered a roadblock. The ...

Tips for creating a conditional CSS pseudo-element using styled-components

I am attempting to create a styled-component with conditional pseudo-elements, but I am having trouble getting it to work properly. Could someone confirm if the syntax I am using is correct? For the context: I want to achieve a scenario where if isSelecte ...

Restrict allowable javascript input for users

I am looking for a way to enable users to input their own mathematical formulas into a field that can be executed via JavaScript. However, I want to restrict them to only entering math-related code and limit their access to the Math object. My goal is to ...

When a character array is passed to a C function, its value may diminish

I'm facing an issue when passing a char[] to a function where it loses its value. Despite being able to pass it to other functions successfully, when passing it to a specific function, the string stored in the array disappears. Here is the code snippe ...

Using ThreeJS to assign various textures based on the position of the object

Recently, I delved into the world of ThreeJS and embarked on creating a model of the Earth using a Sphere mesh. Alongside this, I crafted a model of the Sun and now desire to infuse two distinct textures onto the Earth model based on its orientation. Speci ...