R.M.Jagan
R.M.Jagan

Reputation: 35

is this the default working of reduce method?

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

Condition for the second object executes to true but for the first object, it executes to false (it must be true).

reduce function fetches the Quantity from the second object correctly for the first obj it returns null. Why is it so??

Upvotes: 1

Views: 54

Answers (2)

Ele
Ele

Reputation: 33726

I don't know what's the purpose of the function map, probably you want to use the function forEach instead because it seems you want to loop.

Remember, the function map it's used for transforming the objects of a source array into a new structure in a new array.

Likewise, I think a possible approach should be the function find which finds the first match (according to a 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);
});

Upvotes: 0

Jamiec
Jamiec

Reputation: 136154

A nuance of reduce is that, if you do not provide a seed value the first call to the function passes the first and second element.

The other issue with your code is that you need to return init value from reduce

Also, no need to use map just use forEach if youre not interested in the result of map

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

Upvotes: 1

Related Questions