I Have this array:
var arrayExample = [
{productId: 1, quantity: 2, name: example, description: example},
{productId: 1, quantity: 2, name: example, description: example},
{productId: 1, quantity: 2, name: example, description: example},
{productId: 1, quantity: 2, name: example, description: example}];
My question is
How do I get all the items of the array but taking in every object only the productId and quantity?
Thus having an array that contains all the objects but only with the two values?
The number of the objects of the array is variable
Result:
var arrayExampleNew = [
{productId: 1, quantity: 2},
{productId: 1, quantity: 2},
{productId: 1, quantity: 2},
{productId: 1, quantity: 2}];
sorry for my English
You could just map it
var arrayExample = [{
productId: 1,
quantity: 2,
name: 'example',
description: 'example'
}, {
productId: 1,
quantity: 2,
name: 'example',
description: 'example'
}, {
productId: 1,
quantity: 2,
name: 'example',
description: 'example'
}, {
productId: 1,
quantity: 2,
name: 'example',
description: 'example'
}];
var arr = arrayExample.map(function(item) {
return {productId : item.productId, quantity : item.quantity }
});
console.log(arr)
ES2015:
const arrayExampleNew = arrayExample.map(({productId, quantity}) => ({productId, quantity}));
Related
I am trying pushing the name but in the console log I see just a number and not the actual name
What am i doing wrong??
const cartItems = [{
id: 1,
name: "Soup",
price: 3,
category: "starters",
count: 1
},
{
id: 2,
name: "Pâté",
price: 5,
category: "starters",
count: 1
},
{
id: 9,
name: "Sticky toffee",
price: 18,
category: "desserts",
count: 1
}
]
var dishesArray = [];
var groupByCategory = []
cartItems.reduce(function(res, value) {
if (!res[value.category]) {
res[value.category] = {
category: value.category,
count: 0,
dishes: dishesArray.push(value.name), // problem here
};
groupByCategory.push(res[value.category]);
}
res[value.category].count += value.count;
return res;
}, {});
console.log(groupByCategory)
Expected output
[{category: "starters", count: 2, dishes:["Soup","Pâté"]},
{category: "desserts", count: 1, dishes:["Sticky toffee"]}]
As mentioned, a push returns an int
I believe you are looking for this much shortened reduce
const cartItems = [
{ id: 1, name: "Soup", price: 3, category: "starters", count: 1 },
{ id: 2, name: "Pâté", price: 5, category: "starters", count: 1 },
{ id: 9, name: "Sticky toffee", price: 18, category: "desserts", count: 1}
];
const groupByCategory = cartItems.reduce(function(res, value) {
const cat = value.category;
res[cat] = res[cat] || { category: cat, count: 0, dishes: [] };
res[cat].count += value.count;
res[cat].dishes.push(value.name)
return res;
}, {});
console.log(groupByCategory)
I have an array containing several hundred objects, each of which has a category. I wish to return an object that lists out the categories with a count of the number of items for each category.
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
How would I loop through the object and create a new object that contains just the two categories and how many of each per category?
Desired output:
{vehicle: 4, animal: 3}
Code:
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const final = {};
arr.forEach((v) => {
const tst = v.category;
console.log(tst);
if (tst in final){
console.log('found one');
}
});
//console.log(final);
You can use reduce
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const categories = arr.reduce((acc, cur) => {
acc[cur.category] = (acc[cur.category] || 0) + 1
return acc;
}, {})
console.log(categories)
edit:
Now, after a year a would wrt this like that
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const categories = arr.reduce((acc, cur) => Object.assign(acc, {
[cur.category]: (acc[cur.category] || 0) + 1,
}), {})
console.log(categories)
It looks like the category will always exist, so you don't need to check whether it exists, but what it contains; take what it contains and increment that property on the final object:
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const final = {};
for (const { category } of arr) {
final[category] = (final[category] || 0) + 1;
};
console.log(final);
You have the right idea regarding looping over the array and checking if the category was already encountered. What you're missing is initializing a counter when you find a new category and incrementing it the next time that category is encountered:
const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
const final = {};
arr.forEach((v) => {
const cat = v.category;
if (cat in final) {
final[cat]++;
} else {
final[cat] = 1;
}
});
console.log(final);
const arr = [
{ id: 1, name: 'ford', category: 'vehicle' },
{ id: 2, name: 'pig', category: 'animal' },
{ id: 3, name: 'dog', category: 'animal' },
{ id: 4, name: 'chev', category: 'vehicle' },
{ id: 5, name: 'cat', category: 'animal' },
{ id: 6, name: 'jeep', category: 'vehicle' },
{ id: 7, name: 'honda', category: 'vehicle' },
]
// this will hold the results
const result = {}
for (const item of arr) {
// we have not encountered such category before
if (result[item.category] === undefined) {
// setting this category to 1
result[item.category] = 1
// we encountered such category before
} else {
// addint +1 to it
result[item.category] += 1
}
}
console.log(result)
I am having an array of objects like below
[
{id: 1, name: 'test1', order: 1},
{id: 2, name: 'qos1', order: 2},
{id: 3, name: 'qos2', order: 3}
]
Instead of deleting the object, I am setting a flag like below
[
{id: 1, name: 'test1', order: 1},
{id: 2, name: 'qos1', isDeleted: true, order: 2},
{id: 3, name: 'qos2', order: 3}
]
Now i would like to update the order in the array which is not deleted like below
[
{id: 1, name: 'test1', order: 1},
{id: 2, name: 'qos1', isDeleted: true, order: 2},
{id: 3, name: 'qos2', order: 2}
]
I have used forEach and added a condition like below
array.forEach((a, i) => {
if(!a.isDeleted) {
a.order = i + 1
}
});
But it accounts the index of the object which has isDeleted.But there is one more approach in which i can filter the object which has no isDeleted flag like below
const updatedArray = array.filter((a) => !a.isDeleted);
Which returns the object which has no isDeleted flag but i need the isDeleted object as well in the array but the order should consider only for the non-deleted objects.
You could use a closure over the order and update if necessary.
const data = [{id: 1, name: 'test1', order: 1}, {id: 2, name: 'qos1', isDeleted: true, order: 2}, {id: 3, name: 'qos2', order: 3}];
data.forEach((order => o => {
if (!o.isDeleted) o.order = order++;
})(1))
console.log(data);
Create an external counter, and only increment it if the item is not deleted:
const arr = [{id: 1, name: 'test1', order: 1}, {id: 2, name: 'qos1', isDeleted: true, order: 2}, {id: 3, name: 'qos2', order: 3}]
let counter = 1
arr.forEach(item => {
item.order = counter
counter += !item.isDeleted // casting boolean to number false - 0, true - 1
})
console.log(arr)
I'm trying to convert an array of objects where i return duplicated objects if the object properties quantity is greater than 1.
const objects = [
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
// desired return
[
{ id: 1, name: "Scissor", price: 2 }
{ id: 1, name: "Scissor", price: 2 }
{ id: 1, name: "Scissor", price: 2 }
{ id: 2, name: "Hat", price: 6.5}
{ id: 3, name: "Socks", price: 0.5 }
{ id: 3, name: "Socks", price: 0.5 }
{ id: 3, name: "Socks", price: 0.5 }
{ id: 3, name: "Socks", price: 0.5 }
{ id: 3, name: "Socks", price: 0.5 }
]
My code:
const objects = [
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
let newObjects= [];
Object.entries(objects).forEach(([key, value]) => {
for (let i=0; i < value.quantity; i++){
newObjects.push({ id: value.id, name: value.name, price: value.price})
}
});
console.log(newObjects);
So my code above does work, does return what i wanted, however i feel like there is a better/smoother and more of ES6 and beyond method. Could anyone please suggest a better way?
You could use .fill() and .flatMap().
const objects = [
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
let newObjects = objects.flatMap(e=>
Array(e.quantity).fill({id: e.id, name: e.name, price: e.price})
);
console.log(newObjects);
You can use an array reduce along with an array fill.
The map is required only if you want to have unique references otherwise you can fill using the same object.
const objects = [
{ id: 1, name: "Scissor", price: 2, quantity: 3 },
{ id: 2, name: "Hat", price: 6.5, quantity: 1 },
{ id: 3, name: "Socks", price: 0.5, quantity: 5 },
];
const output = objects.reduce((a, c) => {
return a.concat(Array(c.quantity).fill({}).map(x=>({
id: c.id,
name: c.name,
price: c.price
})))
}, []);
console.log(output)
Here I have two arrays array1 and array2 I want to find ids from array1 which array1's names matched with array2 values how to find ids in javascript ?
array1:
[ {id: 1, name: "Hindi"}
{id: 2, name: "English"}
{id: 3, name: "French"}
{id: 4, name: "Russian"}
{id: 5, name: "Urdu"}
{id: 6, name: "Japanese"}
]
array2:
["Hindi", "Russian", "Urdu"]
I tried this code
console.log(array1.find(x => x.name === array2).id;
You can use filter() to get objects whose names are in the array.Then use map() to convert array of values to array of ids.
In your code you are comparing the string with array x.name === array2. You should use includes()
let arr = [ {id: 1, name: "Hindi"}, {id: 2, name: "English"}, {id: 3, name: "French"}, {id: 4, name: "Russian"}, {id: 5, name: "Urdu"}, {id: 6, name: "Japanese"} ]
let lang = ["Hindi", "Russian", "Urdu"];
let res = arr.filter(x => lang.includes(x.name)).map(x => x.id);
console.log(res)
You should use filter method in combination with map and destructuring
let arr1 = [ {id: 1, name: "Hindi"}, {id: 2, name: "English"}, {id: 3, name: "French"}, {id: 4, name: "Russian"}, {id: 5, name: "Urdu"}, {id: 6, name: "Japanese"} ], arr2 = ["Hindi", "Russian", "Urdu"];
console.log(arr1.filter(({name}) => arr2.includes(name)).map(({id}) => id));
Try this:
var a = [{
id: 1,
name: "Hindi"
}, {
id: 2,
name: "English"
}, {
id: 3,
name: "French"
}, {
id: 4,
name: "Russian"
}, {
id: 5,
name: "Urdu"
}, {
id: 6,
name: "Japanese"
}]
var b = ["Hindi", "Russian", "Urdu"];
var c = a.filter(function(i){
return b.indexOf(i.name)>-1;
});
console.log(c); // New Array with filtered values
This will work too :)
var a1 = [{
id: 1,
name: "Hindi"
}, {
id: 2,
name: "English"
}, {
id: 3,
name: "French"
}, {
id: 4,
name: "Russian"
}, {
id: 5,
name: "Urdu"
}, {
id: 6,
name: "Japanese"
}]
var a2 = ["Hindi", "Russian", "Urdu"];
var filter = a1.filter(function(i) {
return a2.indexOf(i.name) > -1;
}).map(function(obj) {
return obj.id;
});;
console.log(filter);