Does the reduce method work by default like this?

const product_list=[{id:1},{id:2}]
const temp_products=[{id:1,quantity:10},{id:2,quantity:20}]
product_list.map(prod=>{
    console.log(temp_products.reduce((init,curr_prod)=>{
       return curr_prod.id == prod.id ? curr_prod.quantity : null
    }))
})

// null
// 20

The condition for the second object evaluates to true, but unfortunately, for the first object, it evaluates to false when it should be true.

The reduce function successfully retrieves the quantity from the second object, however, for the first object, it returns null instead. Why is this happening?

Answer №1

An interesting aspect of the reduce function is that when a seed value is not provided, the first call combines the first and second elements.

Your code also needs to ensure that the init value is returned from the reduce function.

Furthermore, instead of using map, consider using forEach if you are not concerned with the result of the map operation.

const product_list=[{id:1},{id:2}]
const temp_products=[{id:1,quantity:10},{id:2,quantity:20}]
product_list.forEach(prod=>{
    console.log(temp_products.reduce((init,curr_prod)=>{
       return curr_prod.id == prod.id ? curr_prod.quantity : init
    },null))
})

// 10
// 20

Answer №2

It's unclear what the intention behind using the map function is in this scenario. Perhaps considering the forEach function would be more appropriate since it appears that a looping operation is desired.

To clarify, the map function is typically utilized for transforming objects within a source array into a new structure within a separate array.

Alternatively, you might want to explore using the find function which identifies the first matching item (based on a specified condition) within an array.

const product_list = [{
  id: 1
}, {
  id: 2
}]
const temp_products = [{
  id: 1,
  quantity: 10
}, {
  id: 2,
  quantity: 20
}];

product_list.forEach(prod => {
  let found = temp_products.find(curr_prod => {
    return curr_prod.id == prod.id;
  });
  
  if (found) 
    console.log(found.quantity);
});

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

The visual representation is not being generated (three.js)

I recently designed a basic scene in three.js, however I am facing an issue where it does not seem to work with the canvas renderer, even though it should work correctly. Here is the code: http://jsfiddle.net/PRkcJ/ The scene only functions properly when ...

Node.js reads and writes a JSON file, encountering issues with another application in the process

I'm currently facing an issue with my node.js server (express.js) and a json file used for reading and writing data through a simple API. Interestingly, when the node.js server is stopped, another application can add data to the json file without any ...

Obtain non-numeric parameters from the URL in Angular 2 by subscribing to

How do I handle subscribing to a non-numeric parameter from a URL? Can the local variable inside my lambda function params => {} only be a number? Here's my code: getRecordDetail() { this.sub = this.activatedRoute.params.subscribe( ...

Issues with AngularJS email validation specifically related to domain names are causing errors

Hello, I'm currently working on an AngularJS application where I'm implementing email validation. I'm facing an issue where I expect an error message to appear when I enter 'test@test', but it's not working as intended. Here ...

Encountered a glitch while trying to install React JS using npx create-react-app xyz

After entering the command in the terminal, I encountered an error stating: npm Err! code-ENOENT npm Err! syscall lstat npm Err! path Interestingly, this same command worked perfectly on my instructor's laptops. For reference, I have attached a snaps ...

Tips for preserving state with history.replaceState

Recently, I experimented with the window.history.replaceState function in order to display a specific URL in the browser. window.history.replaceState("", "", "newurl.php"); Although the method successfully changed the URL, I found myself wondering about t ...

Take the inputs, calculate the total by multiplying with the price, and then show

I'm in the process of developing a simple PHP form for an online t-shirt order system. Most aspects are running smoothly, but I'm facing issues with the final calculations. My goal is to combine the quantities based on sizes, multiply them by the ...

Deleting a node from a Swift SpriteKit array

I am currently developing a game for iOS using spritekit/swift. Within my scene, I have declared an array of SKSpriteNode like so: var spritesTree = [SKSpriteNode]() I populate this array using a function and then add them to the scene as shown below: ...

What is the functionality of the protection against AngularJS JSON vulnerability?

When working with JSONs in Angular, it is recommended to prefix them with )]}'\n for added protection against potential JSON vulnerability: A JSON vulnerability could allow a third-party website to transform your JSON resource URL into a JSONP ...

Storing a JSON as a cookie in a Django response

Is there a way to store a dictionary/json object in a client-side cookie from Django and retrieve it as a JavaScript object? response = HttpResponseRedirect(reverse('app:home')) response.set_cookie('cookiekey', 'value') retu ...

PHP Form encountering error due to JSON decoding following an AJAX request

After extensive research and much confusion, I have finally decided to seek help here. I am able to make my AJAX request post successfully in every format except JSON. I am eager to understand JSON so that I can start using it right away instead of learni ...

Incorporate a 'back' button in the tab content of vue-form-wizard

Currently, I'm working on implementing a vue form wizard from the repository: https://github.com/BinarCode/vue-form-wizard My challenge is to include a button in the second tab-content itself instead of having it placed in the footer. I attempted th ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Creating a personalized image download feature in PhotoSwipe.js

I am currently working on a project that involves using the PhotoSwipe gallery. At line 175, there is code url:items[0].hqImage. I want to use the index of the current image instead of 0. How can I achieve this? I attempted to utilize the pswp.listen(&ap ...

Issue with Empty Date Time Format in Vue2 Date-Picker

In our company, we use vue2-datepicker to manage the starting and ending times of meetings. The dates are stored in "YYYY-MM-DD HH:mm" format on the backend, but we convert them to "DD-MM-YYYY HH:mm" format when retrieving the data in the mounted() hook. T ...

Efficiently reducing the size of a CSS selector string with javascript

Is there a library that already performs this function? I've only been able to find online tools. The reason I am interested in accomplishing this task using JavaScript is because I need to ensure that the strings a > b, a and a> b,a are conside ...

Hide multiple divs with similar ids in JQuery when clicking outside of them

Is there a way to hide all div elements with similar id if none of them are clicked on? Currently, my code only works for the first div because I am using index[0] to retrieve the id. How can I make it work for all ids? Below is the code snippet: $(win ...

How can I utilize JQ to display two specific objects located within an array in a JSON file?

My Json file begins with two objects containing description and rtmp_url details. I am striving to extract only these two fields. { "features": [ { "type": "Feature", "geometry": ...

Drop down menus fail to appear after the screen has been resized

Creating responsive menus involves using ordered and unordered lists, along with CSS for styling. I have added a script to dynamically generate dropdown menus, but encountered an issue where nothing appears on the screen upon resizing - only the backgrou ...

Challenges with Input Nesting

Why is the word "undefined" appearing on top of my text? function printName() { document.write('My name is John Doe.'); } function printAge() { printName(); document.write('I am 47 years old.'); } document.querySelector(&ap ...