Write a valueStock function that takes an array of products as a parameter

Viewed 74

Write a valueStock function that takes an array of products as a parameter. The function must return a new arrangement with objects that have the name of each product and the total value of the stock.

var products= [{ name: 'TV LCD', price: 100, stock: 50 }, { name: 'pc', price: 500, stock: 50 }, { name: 'Iphone', price: 1000, stock: 10 }]
var valorStock= function(arreglo){
  var array=[]
   for(var i=0; i<arreglo.length; i++){
      array[productos[i]["name"]]=productos[i]["price"]*["stock"]

   }
   return array
}
console.log(valorStock(productos))

I expect this output:[{ TV LCD: 5000 }, { Computadora: 25000 }, { Iphone: 10000 }]

3 Answers

The function can be achieved in 1 line if you take advantage of Array.prototype.map and computed property names:

var products = [{
  name: 'TV LCD',
  price: 100,
  stock: 50
}, {
  name: 'pc',
  price: 500,
  stock: 50
}, {
  name: 'Iphone',
  price: 1000,
  stock: 10
}];

//This is the function you need
const valueStock = arr => arr.map(el => ({[el.name]: el.price * el.stock}));

console.log(valueStock(products));

You can first keep track of the products in an object and then convert it to an array using Object.entries:

var products = [{
  name: 'TV LCD',
  price: 100,
  stock: 50
}, {
  name: 'pc',
  price: 500,
  stock: 50
}, {
  name: 'Iphone',
  price: 1000,
  stock: 10
}]

var valorStock = function(arreglo) {
  var result = {};
  arreglo.forEach(({name, price, stock}) => {
    result[name] = result[name] || 0;
    result[name] += price * stock;
  });
  return Object.entries(result).map(([k, v]) => ({[k]: v}));
}
console.log(valorStock(products))

If each element in products is unique (has a unique name), you can also simply get your result with map:

var products = [{
  name: 'TV LCD',
  price: 100,
  stock: 50
}, {
  name: 'pc',
  price: 500,
  stock: 50
}, {
  name: 'Iphone',
  price: 1000,
  stock: 10
}]

var valorStock = function(arreglo) {
  return arreglo.map(({name, price, stock}) => ({[name]: price * stock}))
}
console.log(valorStock(products))

You can do something like this.

var products = [{
  name: 'TV LCD',
  price: 100,
  stock: 50
}, {
  name: 'pc',
  price: 500,
  stock: 50
}, {
  name: 'Iphone',
  price: 1000,
  stock: 10
}]
var valorStock = function(arreglo) {
  var array = []
  for (var i = 0, p; p = arreglo[i]; i++) {
    var obj = {};
    obj[p.name] = p.price * p.stock;
    array.push(obj);

  }
  return array
}

// or better
var valorStock1 = function(arreglo) {
  return arreglo.map(p => {
    var obj = {};
    obj[p.name] = p.price * p.stock;
    return obj;
  });
}

console.log(valorStock(products));
console.log(valorStock1(products));

Related