Avoid using reduce in JavaScript

I'm attempting to extract specific values from an object with the status of 'xyz'

user.friends =
CoreMongooseArray [
{ _id: 5b11824350c0011afe9ca310,
user:
 { profile: [Object],
   _id: 5b11805a50c0011afe9ca2fe,
   username: 'user1' },
status: 'abc' },
{ _id: 5b191033d240ab4a10ffb54f,
user:
 { profile: [Object],
   _id: 5b0ec81f958f5b4919b83c40,
   username: 'user2' },
status: 'xyz' } ]

I am utilizing

user.friends.reduce((a, t) => a + (t.type === 'xyz' ? 0 : 1), 0);

However, instead of only returning the object with the username user2 like I expect, it is only returning 1. Why is this happening?

Answer №1

Why does it only return the number 1 instead of the object with the username user2?

It returns 1 because that's the last value returned by your callback function when using the reduce method.

If you are looking to find a specific object in an array based on a certain criterion, using reduce may not be the best approach. Instead, consider using the find method:

const oneXYZFriend = user.friends.find(e => e.status === 'xyz');

(Note that I changed the comparison from e.type === 'xyz' to e.status === 'xyz' assuming your objects have a status property, not a type property.)

If you need to find multiple objects in an array that meet a given criteria, you should use filter:

const xyzFriends = user.friends.filter(e => e.status === 'xyz');

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

Deleting a DOM element within an element that has been created by an external script

On a webpage, I have third-party ad content that is generated by an external script. This content has a delay in loading. My goal is to eliminate a line break from the ad content, but this can only be done once the external script finishes loading and all ...

Is there a way for me to retrieve a variable from outside a function?

I'm trying to access a variable outside of the function in Next.js. I want to retrieve the 'name' from the data object after making an API call. let getDetail = async () => { let body = { code: '12', provider: & ...

The function dispatch is not recognized and will be removed from the database. An error will be generated indicating that dispatch is not a valid function

There seems to be an issue with the delete function in Ticket Actions as it is giving an error that dispatch is not a function. The goal here is to enable users to delete specific tickets by clicking on them and also provide an option to edit the ticket. ...

Obtain data from jQuery Data row

I am currently working on an asp.net page where I have implemented jQuery datatables. Below is a snippet of the code: <% foreach (SubmissionSearchResult result in SearchResults) {%> <tr data-name='<%=result.ID %>'> For each r ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

Modify a section of an HTML text's formatting

function changeEveryCharColor(id) { var part; var whole = ""; var cool1 = document.getElementById(id).innerHTML; console.log(cool1); for(var i = 0; i < cool1.length; i++) { color1 = getRandomInt(255); ...

Using jest in typescript to simulate HttpRequest body and InvocationContext in @azure/functions

I have the following function and I am trying to write a test for it, but I'm having trouble figuring out how to mock HttpRequest import { app, HttpRequest, HttpResponseInit, InvocationContext } from "@azure/functions"; export async function ...

Incorporating additional value attributes without replacing the existing ones

Is there a way to add a value attribute through jQuery without removing the old attribute, similar to how addClass works? I have 7 input fields that are being typed in, and I need to combine them into one word and pass it to another input field. When I try ...

The loading animation does not appear in the NextJS 14 - loading.tsx component while a GET request is being processed

Component with 500 photos displayed on my page: 'use client'; import { useEffect, useState } from 'react'; import { wait } from '@/components/loaders/skeletons'; export default function Postings() { const [photos, setPhotos ...

Hindering advancement: Bootstrap Form Wizard causing roadblocks

I am currently facing an issue with my form wizard setup. I want to prevent the user from advancing to the next step when the success key in my json is set to false. It seems like the project is utilizing the bootstrap wizard plugin. You can find more in ...

Create a new object in Three.js every x seconds and continuously move each object forward in the Z-axis direction

I am currently developing a Three.js endless runner game where the player controls a character dodging cars on a moving road. At this early stage of development, my main challenge is to make the hero character appear to be moving forward while creating the ...

Running React Boilerplate with forever is a great way to ensure your application stays

I plan on keeping the react-boilerplate application running indefinitely on the server. I recently came across forever, but I'm uncertain about how to pass parameters to it. The command to start the server looks like this: PORT=80 npm run start:produ ...

Jquery Ajax failing to retrieve a response

Here's the jQuery script I am using to fetch data from my server: $(".login_button").click(function () { var username = $(".username").val(); var userkey = $(".userkey").val(); $.ajax({ type: "GET", url: "http://192.168.0. ...

Attempting to modify read-only properties is prohibited in strict mode within the context of [background: url({{XXX}}) no-repeat center center

I encountered an issue in Edge, but everything works fine in Chrome. I can't figure out what's causing the problem... <div class="container-fluid project_img" style="background: url({{_project.images.web}}) no-repeat center center;"> ...

Tips for integrating PHP into a Bootstrap modal dialog

After discovering and modifying a php script designed to process contact form content and display alerts on a Bootstrap 3 modal window, I encountered some issues. While I was able to successfully display errors and show the modal onload without any php con ...

Bug found in React Native when navigating between screens causing the screen size to shrink

Check out the image below. https://i.stack.imgur.com/t04Vv.png Issue: Whenever I switch to a new scene, the previous screen appears to shrink or move upwards. This behavior is not consistent with the usual user experience seen on Apple apps - any thought ...

Receiving the error message "undefined is not a function" when using THREE.PointerLockControls()

I am working on implementing a moving camera in THREE like the example below: function initializeThree(){ scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(75,window.innerWidth/window.innerHeight,0.1,1000); renderer = new THREE.C ...

Is it possible for Eslint to give a warning if an import statement is missing?

I'm currently working with nodejs and regular javascript, utilizing eslint to identify errors in my code. However, I have noticed that eslint fails to detect when I forget to import a package into my code. The following example highlights this issue. ...

AngularJS: Customizable URL Prefix for Dynamic Routing

I am facing a challenge with my large Angular app that is currently accessible through the following URL: http://myangularapp.com/app/index.html#/ In order to support multiple users, I need to dynamically inject a name into the URL that I will be sharing ...

Sending an email through Node.js with SendGrid is not a challenge

I've got this Mailer.js file const sendgrid = require('sendgrid'); const helper = sendgrid.mail; const keys = require('../config/keys'); class Mailer extends helper.Mail { constructor({ subject, recipients ...