0

I want to store and display all(including repeated) objects but it only stores distinct(unique) values.

The good thing is total is adding all the values including reoccurring The Bad thing is indistinctresult cannot store reoccurring object
for loop also does not work

if (req.isAuthenticated()) {
    User.find({ _id: req.user._id }, function (err, cartitem) {
      var noofcartitem = cartitem[0].cart_array.length;

      product.find({ _id: cartitem[0].cart_array }, function (err, result) {
        var total = 0;
        var x;
        var indistinctresult = [];  ***//stores only distinct(Unique) values*** 
        for (x in result) {
          total += result[x].price;
          indistinctresult.push(result[x]);
        }
        console.log(indistinctresult); **//expected to log all(including non unique) values**
        res.render("cart", {
          cart_array: noofcartitem,
          total: total,
          cartproduct: indistinctresult,
        });
      });
    });
  } else {
    res.redirect("/login");
  }
Jay
  • 3
  • 5
  • Does this answer your question? [Get all unique values in a JavaScript array (remove duplicates)](https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates) – mgm793 Oct 05 '20 at 06:23
  • What does this line do: `for (x in result) { ... }`? `x` is not assigned a value anywhere in your code. – Terry Oct 05 '20 at 06:26
  • x loop to the number of items in result. – Jay Oct 05 '20 at 06:39
  • First step, replace `for (x in result)` with `for (let x=0; x – slebetman Oct 05 '20 at 06:54
  • same result sir, the problem is indistinctresult stores only unique values. – Jay Oct 05 '20 at 07:15

2 Answers2

1

I see you are using for..in loop for iterating through array. It's not a good idea.

The following link might be helpful to you.

Why is using "for...in" for array iteration a bad idea?

Barathi M
  • 46
  • 3
  • can you please suggest me the way I can get my job done because i tried for loop the problem was that i cannot acess the variable out of loop. – Jay Oct 05 '20 at 07:01
  • the result is too long. – Jay Oct 06 '20 at 07:31
  • I think your query result itself contains only unique values. Then how you are expecting indistinct values? How you are defining your unique items? – Barathi M Oct 06 '20 at 09:44
  • no,total variable is adding reoccurring values and on logging the result inside loop is also printing reoccuring object. – Jay Oct 06 '20 at 13:50
0
const x = [1, 2, 3, 1]
const y = []
for (let i=0; i<x.length; i++) {
    y.push(x[i]);  
}
console.log(y);

OUTPUT: [1, 2, 3, 1]
Replace you for..in loop with for loop with index.