Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a string from object array

Tags:

javascript

I have two arrays as below:

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

I want to loop through the array and print the following:

  1. If product 1, output you have 2 One Plus
  2. If product 2, output you have 1 One Plus and 1 Apple

Below is the code that I tried.

var product1 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "One Plus"
    }
  ];
var product2 = [
    {
      "Brand": "One Plus"
    },
    {
      "Brand": "Apple"
    }
  ];

counter1 = {}
product1.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter1[key] = (counter1[key] || 0) + 1
});
console.log(counter1);
counter2 = {}
product2.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter2[key] = (counter2[key] || 0) + 1
});
console.log(counter2);

I’m able to get the JSON output, but how can I get it in the sentence format?

like image 538
user3872094 Avatar asked Dec 10 '25 17:12

user3872094


2 Answers

How about this?

var product1 = [{
    "Brand": "One Plus"
  },
  {
    "Brand": "One Plus"
  }
];
var product2 = [{
    "Brand": "One Plus"
  },
  {
    "Brand": "Apple"
  }
];

function countProducts(arr) {
  let counter = arr.reduce((acc, val) =>
    (acc[val.Brand] = (acc[val.Brand] || 0) + 1, acc), {});
  let strings = Object.keys(counter).map(k => `${counter[k]} ${k}`);
  return `You have ${strings.join(' and ')}`;
}

console.log(countProducts(product1));

console.log(countProducts(product2));
like image 103
gyohza Avatar answered Dec 13 '25 07:12

gyohza


const product1 = [
  {Brand: "One Plus"},
  {Brand: "One Plus"},
];
const product2 = [
  {Brand: "One Plus"},
  {Brand: "Apple"},
];

function whatYouHaveIn(list) {
  return `You have ` + Object.entries(list.reduce((a, c) => {
    a[c.Brand] = a[c.Brand] || 0;
    a[c.Brand]++;
    return a;
  }, {})).map(([brand, count]) => `${count} ${brand}`).join(` and `);
}

console.log(whatYouHaveIn(product1));

console.log(whatYouHaveIn(product2));
like image 45
Chase Avatar answered Dec 13 '25 06:12

Chase



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!