Sorting array of objects by price (lowest to highest) - javascript

Below is some of the data that I'm currently working with while making a web app in React.js, right now I'm trying to sort the array of objects by price lowest to highest so that when a button is clicked the array is sorted and is displayed on the DOM from lowest to highest.
A couple of things I'm having to consider is that the prices are all comprised as strings with a '$' character as the first character (EX: '$18') and the second object in the arrays price is "Suggested Donation".
studios: [
{
name: "Whole Yoga",
price: "$17.00"
},
{
name: "Rino Yoga Social",
price: "Suggested Donation"
},
{
name: "Samadhi Yoga",
price: "$20.00"
},
{
name: "Corepower Yoga",
price: "$25.00"
},
{
name: "The River Yoga",
price: "$20.00"
},
{
name: "Endorphin Yoga",
price: "$10.00"
},
{
name: "Kindness Yoga",
price: "$20.00"
},
{
name: "Yoga High",
price: "$15.00"
},
{
name: "Freyja Project",
price: "$22.00"
},
{
name: "Kula Yoga",
price: "$17.00"
}
]
So far I used a while loop to remove the '$' character at the beginning of the string then used .replace() method to replace "Suggested Donation" with '00.00' and parseInt all the prices.
The issue I'm having now is that the new array of sorted prices have nothing to do with the original data (nothing linking them) so I'm just returning an array of sorted prices that I cant do anything with. Anyone have any ideas on how I should go about this?
priceFilter = () => {
let newArr = []
return this.props.studios.filter( studio => {
let price = studio.price;
while(price.charAt(0) === '$') {
price = price.substr(1);
}
price = price.replace('Suggested Donation', '00.00')
let parsedPrice = parseInt(price);
newArr.push(parsedPrice)
return newArr.sort((a,b) => (a - b));
})
}

Convert your values to numbers. Based on your code your suggest price should be 0, so we use that if the price does not start with a dollar sign '$'
const studios = [
{
name: "Whole Yoga",
price: "$17.00"
},
{
name: "Rino Yoga Social",
price: "Suggested Donation"
},
{
name: "Samadhi Yoga",
price: "$20.00"
},
{
name: "Corepower Yoga",
price: "$25.00"
},
{
name: "The River Yoga",
price: "$20.00"
},
{
name: "Endorphin Yoga",
price: "$10.00"
},
{
name: "Kindness Yoga",
price: "$20.00"
},
{
name: "Yoga High",
price: "$15.00"
},
{
name: "Freyja Project",
price: "$22.00"
},
{
name: "Kula Yoga",
price: "$17.00"
}
]
priceFilter = (vals) => {
return vals.sort((a,b) => {
const aPrice = a.price[0] === '$' ? parseFloat(a.price.slice(1,-1)) : 0;
const bPrice = b.price[0] === '$' ? parseFloat(b.price.slice(1,-1)) : 0;
return aPrice - bPrice;
});
}
console.log(priceFilter(studios));

You can write a custom sort with Array.prototype.sort (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort).
const compare = (a, b) => {
const aPrice = Number(a.price.replace(/[^0-9.-]+/g,""));
const bPrice = Number(b.price.replace(/[^0-9.-]+/g,""));
return aPrice - bPrice
};
const sortedStudios = this.props.studios.sort(compare);

You could take a function for getting the value for sorting and then take the delta as redsult for the sorting method.
const getValue = ({ price }) => +price.slice(1) || 0;
var studios = [{ name: "Whole Yoga", price: "$17.00" }, { name: "Rino Yoga Social", price: "Suggested Donation" }, { name: "Samadhi Yoga", price: "$20.00" }, { name: "Corepower Yoga", price: "$25.00" }, { name: "The River Yoga", price: "$20.00" }, { name: "Endorphin Yoga", price: "$10.00" }, { name: "Kindness Yoga", price: "$20.00" }, { name: "Yoga High", price: "$15.00" }, { name: "Freyja Project", price: "$22.00" }, { name: "Kula Yoga", price: "$17.00" }];
studios.sort((a, b) => getValue(a) - getValue(b));
console.log(studios);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Here you go. :)
let studios = [{
name: "Whole Yoga",
price: "$17.00"
},
{
name: "Rino Yoga Social",
price: "Suggested Donation"
},
{
name: "Samadhi Yoga",
price: "$20.00"
},
{
name: "Corepower Yoga",
price: "$25.00"
},
{
name: "The River Yoga",
price: "$20.00"
},
{
name: "Endorphin Yoga",
price: "$10.00"
},
{
name: "Kindness Yoga",
price: "$20.00"
},
{
name: "Yoga High",
price: "$15.00"
},
{
name: "Freyja Project",
price: "$22.00"
},
{
name: "Kula Yoga",
price: "$17.00"
}
];
console.log("Unsorted", studios);
studios.sort(({
price: a
}, {
price: b
}) => {
//parseFloat will be Nan if it cannot parse the string into a number
//the only problem here is that any non int string will turn into 0
a = parseFloat(a.slice(1), 10) || 0;
b = parseFloat(b.slice(1), 10) || 0;
return a - b;
});
console.log("Sorted", studios);

You probably want to sort objects by price instead of sorting prices:
const studios = [{"name":"Whole Yoga","price":"$17.00"},{"name":"Rino Yoga Social","price":"Suggested Donation"},{"name":"Samadhi Yoga","price":"$20.00"},{"name":"Corepower Yoga","price":"$25.00"},{"name":"The River Yoga","price":"$20.00"},{"name":"Endorphin Yoga","price":"$10.00"},{"name":"Kindness Yoga","price":"$20.00"},{"name":"Yoga High","price":"$15.00"},{"name":"Freyja Project","price":"$22.00"},{"name":"Kula Yoga","price":"$17.00"}];
const parsePrice = x => parseFloat(x.replace(/^\$/, '')) || 0
const sortedStudios = studios
.slice()
.sort((a, b) => parsePrice(a.price) - parsePrice(b.price))
console.log(sortedStudios)

Thanks for the help everyone! This solution worked for me.
priceFilter = () => {
let ordered = studios.sort((a, b) => (a.price > b.price) ? 1 : -1);
let lastElement = ordered.pop();
return ordered.unshift(lastElement);
}

Related

Is there a way to console.log an output only when my loop finishes running and matched no entry

In the code below how do i output try again only when the entire code execution runs and customer's order is not found amongst the product order in the menuItem dictionary.
I want to output this only when customer input doesn't match any product code
let menuItem = {
item_1: {
name: "french burger",
price: 1000,
productCode: 101
},
item_2: {
name: "chicken sharwama",
price: 1500,
productCode: 102
},
item_3: {
name: "pizza",
price: 5000,
productCode: 103
},
item_4: {
name: "beef sharwama",
price: 1500,
productCode: 104
},
item_5: {
name: "smoothie (mix flavor)",
price: 1300,
productCode: 105
}
}
listMenuItem = () => {
for (let i in menuItem) {
console.log(`Order Code: ${menuItem[i].productCode} || ${menuItem[i].name}, ${menuItem[i].price} NGN \n`)
}
}
listMenuItem()
var order = prompt("Enter product code to make your order: ")
console.log(order)
let customerOrder = []
for (let i in menuItem) {
if (menuItem[i].productCode == order) {
customerOrder.push(menuItem[i])
console.log(customerOrder)
console.log(`${menuItem[i].name}, ${menuItem[i].price}`)
} else {
console.log("Product does not exist, try again")
}
}
Your structure makes it harder to use the array methods.
The result is more confusing that it would have been if you just had an object keyed on productCode
let menuItem = {
item_1: {
name: "french burger",
price: 1000,
productCode: 101
},
item_2: {
name: "chicken sharwama",
price: 1500,
productCode: 102
},
item_3: {
name: "pizza",
price: 5000,
productCode: 103
},
item_4: {
name: "beef sharwama",
price: 1500,
productCode: 104
},
item_5: {
name: "smoothie (mix flavor)",
price: 1300,
productCode: 105
}
}
listMenuItem = () => {
for (let i in menuItem) {
console.log(`Order Code: ${menuItem[i].productCode} || ${menuItem[i].name}, ${menuItem[i].price} NGN \n`)
}
}
listMenuItem()
var order = +prompt("Enter product code to make your order: "); // convert the string to number or make the productCode a string in the object
console.log(order)
let customerOrder = Object.entries(menuItem).find(([key,{productCode}]) => productCode === order);
console.log(customerOrder)
if (customerOrder) {
console.log(`I found ${customerOrder[1].name}, ${customerOrder[1].price}`)
}
else {
console.log("Product does not exist, try again")
}

Process array of objects to return least priced per product using JavaScript

Given an array of objects, containing products. A single object contains a single product offer.
Products can have a identical productId, while offerId are unique for each product.
Process the data to get the cheapest priced item for each offer
const data = [
{ productId: 'dhdiwu', offerId: 'd3en', price: '$12.20' },
{ productId: 'dhdiwu', offerId: 's2dr', price: '$8.45' },
{ productId: 'dhdiwu', offerId: 'hy38', price: '$21.21' },
{ productId: 'dowksm', offerId: 'ie8u', price: '$1.77' },
{ productId: 'dowksm', offerId: 'djs3', price: '$24.21' },
{ productId: 'dowksm', offerId: 'pies', price: '$92.36' },
{ productId: 'bdbhsu', offerId: '9wid', price: '$100.98' }
]
const dataArray = data.reduce((prev, t, index, arr) => {
if (typeof prev[t.productId] === 'undefined') {
prev[t.productId] = [];
}
prev[t.productId].push(t);
return prev;
}, {});
let same_id = []
let cheapest = []
Object.keys(dataArray).forEach(i => {
same_id.push(dataArray[i]);
});
console.log(same_id)
//output for now
/*[
[
{ productId: 'dhdiwu', offerId: 'd3en', price: '$12.20' },
{ productId: 'dhdiwu', offerId: 's2dr', price: '$8.45' },
{ productId: 'dhdiwu', offerId: 'hy38', price: '$21.21' }
],
[
{ productId: 'dowksm', offerId: 'ie8u', price: '$1.77' },
{ productId: 'dowksm', offerId: 'djs3', price: '$24.21' },
{ productId: 'dowksm', offerId: 'pies', price: '$92.36' }
],
[ { productId: 'bdbhsu', offerId: '9wid', price: '$100.98' } ]
]*/
I would first start by grouping the products by productId, something like what is suggested here should work: Most efficient method to groupby on an array of objects
function groupByKey(array, key) {
const groupedObject = {}
for (const item of array) {
const value = item[key]
if (groupedObject[value] === undefined) {
groupedObject[value] = []
}
groupedObject[value].push(item)
}
return groupedObject
}
groupByKey(data, 'productId')
Now you have an object with three properties, the unique productID's with each product inside it. Then loop through each one, find the lowest price.
const grouped = groupByKey(data, 'productId');
const lowest = {};
for (const group of Object.keys(grouped)) {
if (!lowest[group]) {
lowest[group] = '';
}
for (const product of grouped[group]) {
if (lowest[group] === '') {
lowest[group] = product.price
}
if (product.price < lowest[group]) {
lowest[group] = product.price;
}
}
}
console.log(lowest);
// {dhdiwu: '$12.20', dowksm: '$1.77', bdbhsu: '$100.98'}
It's a little scrappy, and I'm sure there are some cool one-liners you could build, but that's the general idea.
If I understand correctly, you're looking to find the lowest priced offer for each productId.
You can go with this:
const data = [
{ productId: 'dhdiwu', offerId: 'd3en', price: '$12.20' },
{ productId: 'dhdiwu', offerId: 's2dr', price: '$8.45' },
{ productId: 'dhdiwu', offerId: 'hy38', price: '$21.21' },
{ productId: 'dowksm', offerId: 'ie8u', price: '$1.77' },
{ productId: 'dowksm', offerId: 'djs3', price: '$24.21' },
{ productId: 'dowksm', offerId: 'pies', price: '$92.36' },
{ productId: 'bdbhsu', offerId: '9wid', price: '$100.98' }
]
// group by productId and find the lowest price
const result = data.reduce((acc, { productId, offerId, price }) => {
const current = acc[productId]
if (!current || current.price > price) {
acc[productId] = { offerId, price }
}
return acc
}, {})
console.log(result)
output:
node .\scratch.js
{
dhdiwu: { offerId: 'd3en', price: '$12.20' },
dowksm: { offerId: 'ie8u', price: '$1.77' },
bdbhsu: { offerId: '9wid', price: '$100.98' }
}

How to sum values of an array with products and values and order from ascending?

I'm beginner in JavaScript and I'm rendering a list that contains some products.
A product contains several sizes and each size has its price:
const data = [
{
id: "5286",
name: "Alyssa Ashley White Musk",
description: "Sensual but not overpowering",
categories: ["Fresh"],
sizes: [
{
name: "Sample",
price: 0,
},
{
name: "Normal",
price: 4000,
},
{
name: "Large",
price: 6500,
},
],
},
{
id: "6298",
name: "Euphoria",
description:
"Euphoria by Calvin Klein is a woody, oriental scent has notes of pomegranate, black violet, black orchid, and mahogany.",
categories: ["Floriental"],
sizes: [
{
name: "Normal",
price: 7100,
},
],
},
{
id: "9201",
name: "Emporio Armani",
description:
"Emporio Armani by Giorgio Armani bottles style and sophistication for women all over the world to enjoy.",
categories: ["Floriental"],
sizes: [
{
name: "Sample",
price: 0,
},
{
name: "Normal",
price: 2700,
},
],
},
];
export default data;
What I would like is, for example, sum all sizes of product 1 to get the total value. Sum all sizes of product 2 and getting the total value and so on. After obtaining the sum of all products. Sort the list in ascending ones.
I tried using the reducer function. But as inside each product it contains an array with the respective sizes and prices. I didn't know how to do it.
I put my code into codesandbox
Thank you in advance
It will be good to add totalSize key (which contains the sum of item sizes) on each item using Array.map and sort that using Array.sort.
const data = [
{
id: "5286",
name: "Alyssa Ashley White Musk",
description: "Sensual but not overpowering",
categories: ["Fresh"],
sizes: [
{
name: "Sample",
price: 0,
},
{
name: "Normal",
price: 4000,
},
{
name: "Large",
price: 6500,
},
],
},
{
id: "6298",
name: "Euphoria",
description:
"Euphoria by Calvin Klein is a woody, oriental scent has notes of pomegranate, black violet, black orchid, and mahogany.",
categories: ["Floriental"],
sizes: [
{
name: "Normal",
price: 7100,
},
],
},
{
id: "9201",
name: "Emporio Armani",
description:
"Emporio Armani by Giorgio Armani bottles style and sophistication for women all over the world to enjoy.",
categories: ["Floriental"],
sizes: [
{
name: "Sample",
price: 0,
},
{
name: "Normal",
price: 2700,
},
],
},
];
const result = data.map((item) => ({
...item,
totalSize: item.sizes.reduce((sum, cur) => (sum + cur.price), 0)
})).sort((a, b) => a.totalSize - b.totalSize);
console.log(result);

How, with JavaScript, does one map a list of names with aggregated data values from a related data-item list?

Maybe someone can give me idea how can i do it. So I have array of names ["Tom", "Jane", "Mike", "John"] and also I have array of objects which are purchase reports:
[
{ date: "19/02/2019", name: "Mike", amount: 10 },
{ date: "20/02/2019", name: "Mike", amount: 15 },
{ date: "21/10/2019", name: "Jane", amount: 25 },
{ date: "22/03/2019", name: "John", amount: 30 },
{ date: "19/03/2019", name: "Tom", amount: 15 }
]
I need to get objects which represent a person and the amount they spend overall. [{ name: "Tom", amount: 15 }, { name: "Mike", amount: 25 }, ... I hope you get the idea. How can I achieve this? I try to map the names and filter array of objects but get undefined.
Use a combination of map, filter and reduce to boil down the data:
The first .map is building the object structure, you want e.g. {name: '...', amount: <val>}
in order to get the value for each of the names, you filter the spending by name and reduce the outputed values by adding them.
const names = ["Tom", "Jane", "Mike", "John"];
const spendings = [{
date: "19/02/2019",
name: "Mike",
amount: 10
}, {
date: "20/02/2019",
name: "Mike",
amount: 15
}, {
date: "21/10/2019",
name: "Jane",
amount: 25
}, {
date: "22/03/2019",
name: "John",
amount: 30
}, {
date: "19/03/2019",
name: "Tom",
amount: 15
}];
const result = names.map(name => {
return {
name,
amount: spendings.filter(spending => spending.name === name).reduce((sum, {
amount
}) => sum + amount, 0)
};
});
console.log(result);
You can try this code:
const data = [
{ date: "19/02/2019", name: "Mike", amount: 10 },
{ date: "20/02/2019", name: "Mike", amount: 15 },
{ date: "21/10/2019", name: "Jane", amount: 25 },
{ date: "22/03/2019", name: "John", amount: 30 },
{ date: "19/03/2019", name: "Tom", amount: 15 },
];
const names = ["Tom", "Jane", "Mike", "John"];
const results = names.map((name) => ({
name,
amount: data
.filter(({ name: dataName }) => dataName === name)
.reduce((total, { amount }) => total + amount, 0),
}));
console.log(results);
.as-console-wrapper { min-height: 100%!important; top: 0; }
You can set it up however you like using the javascript filter method.
Eg. If you want to get entries in the array that match name and amount you can write a function like this:
const result = (name, cost) => array.filter(customer => {
return name == customer.name && cost == customer.cost;
});
Running result("Jane", 25) will return this:
[{date: "21/10/2019", name: "Jane", amount: 25}]
You could create an object with the wanted names and add the amount to each property.
const
names = ["Tom", "Jane", "Mike", "John"],
purchases = [{ date:"19/02/2019", name: "Mike", amount: 10 }, { date: "20/02/2019", name: "Mike", amount: 15 }, { date: "21/10/2019", name: "Jane", amount: 25 }, { date: "22/03/2019", name: "John", amount: 30 }, { date: "19/03/2019", name: "Tom", amount: 15 }],
result = purchases.reduce(
(object, { name, amount }) => (object[name] += amount, object),
Object.fromEntries(names.map(name => [name, 0]))
);
console.log(result);
Use Array.reduce on your report array.
And reduce report array into dictionary of overall report for each name.
try first to solve it by your own.
this is my solution :
const dictionaryReports = reports.reduce((prev,curr)=>{
if(!prev[curr.name]) {
return {...prev,prev[curr.name] : curr}
}else{
return {
...prev,
prev[curr.name]:
{
...prev[curr.name],
amount : prev[curr.name].amount + curr.amount
}
}
}
},{})
the output will be :
dictionaryReports = {
Mike : {name:"Mike",amount:25},
Tom : {name:"Tom",amount:15}
}
then you can do
Object.values(dictionaryReports)
You can use the array reduce method on purchases. You don't need the array of names I think it looks useless for the result.
const purchases = [
{ date: "19/02/2019", name: "Mike", amount: 10 },
{ date: "20/02/2019", name: "Mike", amount: 15 },
{ date: "21/10/2019", name: "Jane", amount: 25 },
{ date: "22/03/2019", name: "John", amount: 30 },
{ date: "19/03/2019", name: "Tom", amount: 15 }
]
const overall = purchases.reduce((acc, curr) => {
const currentUser = acc.find(x => x.name === curr.name);
if(currentUser) {
currentUser.amount += curr.amount;
} else {
acc.push({name:curr.name,amount: curr.amount})
}
return acc;
}, []);
This approach is as generic as can be. It combines a map and a reduce method in a way that any data from a given dataset (list of data) and a corresponding (target) value list can be collected for the latter from the former by just providing a start configuration to the above mentioned map-reduce combination ...
const dataset = [
{ date: "19/03/2019", name: "Jerry", amount: 45 },
{ date: "19/02/2019", name: "Mike", amount: 10 },
{ date: "20/02/2019", name: "Mike", amount: 15 },
{ date: "21/10/2019", name: "Jane", amount: 25 },
{ date: "22/03/2019", name: "John", amount: 30 },
{ date: "19/03/2019", name: "Tom", amount: 15 },
{ date: "19/03/2019", name: "Jerry", amount: 15 }
];
function aggregateTargetItemValueFromSourceKey(collector, item) {
const { aggregateValue, sourceKey, targetKey, targetItem } = collector;
if (targetItem[targetKey] === item[targetKey]) {
targetItem[sourceKey] = aggregateValue(targetItem[sourceKey], item[sourceKey]);
}
return collector;
}
function createTargetItemFromBoundDatasetConfig(targetValue) {
const { dataset, aggregateValue, initialValue, sourceKey, targetKey } = this;
return dataset.reduce(aggregateTargetItemValueFromSourceKey, {
aggregateValue,
sourceKey,
targetKey,
targetItem: {
[targetKey]: targetValue,
[sourceKey]: initialValue
}
}).targetItem;
}
console.log(
["Tom", "Jane", "Mike", "John"]
.map(createTargetItemFromBoundDatasetConfig, {
aggregateValue: ((targetValue, sourceValue) => targetValue + sourceValue),
initialValue: 0,
sourceKey: 'amount',
targetKey: 'name',
dataset
})
);
console.log(
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
.map(createTargetItemFromBoundDatasetConfig, {
aggregateValue: ((targetValue, sourceValue) => targetValue.concat(sourceValue)),
initialValue: [],
sourceKey: 'name',
targetKey: 'amount',
dataset
})
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
The second approach is a straightforward one, thus it is less flexible in the result it does produce. Nevertheless, there is at least the option of plainly aggregating the data from any item in the provided dataset, or, as the OP unintentionally might have hinted by the provided name list, one can use the latter for filtering only those items from the dataset list that are actually feature one of its names. ...
const dataset = [
{ date: "19/03/2019", name: "Jerry", amount: 45 },
{ date: "19/02/2019", name: "Mike", amount: 10 },
{ date: "20/02/2019", name: "Mike", amount: 15 },
{ date: "21/10/2019", name: "Jane", amount: 25 },
{ date: "22/03/2019", name: "John", amount: 30 },
{ date: "19/03/2019", name: "Tom", amount: 15 },
{ date: "19/03/2019", name: "Jerry", amount: 15 }
];
const itemNameList = ["Tom", "Jane", "Mike", "John"];
function aggregateItemAmountByItemNameWithOptionalNameCeck(collector, item) {
const { checklist, index, list } = collector;
const itemName = item.name;
const isProceed = (!Array.isArray(checklist) || checklist.includes(itemName))
if (isProceed) {
let targetItem = index[itemName];
if (!targetItem) {
targetItem = index[itemName] = {
name: itemName,
amount: 0
};
list.push(targetItem);
}
targetItem.amount = targetItem.amount + item.amount;
}
return collector;
}
console.log(
'with name check ... ',
dataset.reduce(aggregateItemAmountByItemNameWithOptionalNameCeck, {
checklist: itemNameList,
index: {},
list: []
}).list
);
console.log(
'without name check ... ',
dataset.reduce(aggregateItemAmountByItemNameWithOptionalNameCeck, {
index: {},
list: []
}).list
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

How to add random values in an object array Javascript?

const prod = [{
name: "Sweat",
description: " collection",
price: 150,
},
{
name: "Trousers",
description: "Attire",
price: 243
},
{
name: "T-shirt",
description: "Winter",
},
{
name: "Hoody",
description: "Fashion",
},
{
name: "Pants",
description: "Winter",
},
{
name: "Casual",
description: "Winter",
price: 245,
},
{
name: "Shirt",
description: "Attire",
price: 150,
}
];
Hi, I'm trying to add a random popularity score between 0 - 100, randomly for the products without them using a function.
I've tried to figure out solutions from
https://levelup.gitconnected.com/set-data-structure-in-javascript-62e65908a0e6
and
https://medium.com/front-end-weekly/getting-a-random-item-from-an-array-43e7e18e8796
but still unsure how to add elements to specific indices without the 'popularity' element. Thanks!
Filter the array to the elements you want first, then apply the random number
// function
const addRandomPopularityWhereThereIsNone = products => {
products.filter(p => !p.hasOwnProperty('popularity')).forEach(p => {
p.popularity = Math.floor(Math.random() * 101)
})
}
// call it
addRandomPopularityWhereThereIsNone(products)
Note that this modifies the original array.
For reference:
Array.prototype.filter()
Object.protytype.hasOwnProperty()
Please try the following solution
const products = [{"name":"Pullover Sweat","description":"Winter collection","price":150,"popularity":99},{"name":"Formal Trousers","description":"Attire for men","price":500},{"name":"Winter T-shirt","description":"Winter collection","price":50,"popularity":50},{"name":"New Fashion Hoody","description":"Fashion line","price":200},{"name":"Winter Pants","description":"Winter collection","price":150},{"name":"Casual Coat","description":"Winter collection","price":245,"popularity":78},{"name":"Fine Long Sleeve Shirt","description":"Attire for men","price":150,"popularity":10}];
const output = products.map((product) => {
if ("popularity" in product) {
return { ...product };
}
return { ...product, popularity: generateRandomNumber() };
});
function generateRandomNumber() {
return Math.floor(Math.random() * 100) + 1;
}
console.log(output);
Take a look to array map and the in operator
Use map and nullish coalescing operator (??)
const products = [{"name":"Pullover Sweat","description":"Winter collection","price":150,"popularity":99},{"name":"Formal Trousers","description":"Attire for men","price":500},{"name":"Winter T-shirt","description":"Winter collection","price":50,"popularity":50},{"name":"New Fashion Hoody","description":"Fashion line","price":200},{"name":"Winter Pants","description":"Winter collection","price":150},{"name":"Casual Coat","description":"Winter collection","price":245,"popularity":78},{"name":"Fine Long Sleeve Shirt","description":"Attire for men","price":150,"popularity":10}];
const update = (arr) =>
arr.map(({ popularity, ...product }) => ({
popularity: popularity ?? Math.floor(Math.random() * 100) + 1,
...product,
}));
console.log(update(products));
const products = [{
name: "Pullover Sweat",
description: "Winter collection",
price: 150,
popularity: 99
},
{
name: "Formal Trousers",
description: "Attire for men",
price: 500
},
{
name: "Winter T-shirt",
description: "Winter collection",
price: 50,
popularity: 50
},
{
name: "New Fashion Hoody",
description: "Fashion line",
price: 200
},
{
name: "Winter Pants",
description: "Winter collection",
price: 150
},
{
name: "Casual Coat",
description: "Winter collection",
price: 245,
popularity: 78
},
{
name: "Fine Long Sleeve Shirt",
description: "Attire for men",
price: 150,
popularity: 10
}
];
const addPopularity = products => {
products.filter(p => !p.popularity).map(p => {
p.popularity = Math.floor(Math.random() * 101)
})
return products;
}
console.log(addPopularity(products));

Categories

Resources