Javascript total based on array key [duplicate] - javascript

This question already has answers here:
Sum JavaScript object propertyA values with the same object propertyB in an array of objects
(12 answers)
How to group by and sum an array of objects? [duplicate]
(2 answers)
Closed 4 days ago.
I have a product list retrieved via PHP and I was trying to compute the total quantity per product. I already grouped them using push in javascript. Now I want to achieve that it will compute the total value(QTY) based on the key(Product ID).
[{130493: 1}, {130493: 34}, {141364: 500}, {120798: 336}, {130493: 12} ];
Output should be:
[{130493: 47},{141364: 500},{120798: 336}]
My Code:
let get_list_items = document.querySelectorAll("#mta-product-list .product-list-item");
let get_qty_per_prod = [];
get_list_items.forEach(item=>{
let item_id = item.getAttribute("data-product-id").toString();
let get_current_qty = item.querySelector(`[data-product-id='${item_id}'] .list-product-quantity`).value.toString();
get_qty_per_prod.push({[item_id]:get_current_qty});
});
//get_qty_per_prod = sample output [{130493: 1}, {130493: 34}, {141364: 500}, {120798: 336}, {130493: 12} ];
//trying to compute total per product here...
let total_qty = 0;
let get_total_qty = [];
if(get_qty_per_prod){
get_qty_per_prod.forEach(totalQty=> {
//console.log(totalQty);
if(productId){
total_qty += parseInt(totalQty[productId]);
get_total_qty.push({[productId]:total_qty});
}
});
console.log(get_total_qty);
}

Related

extract sub parameters from array with objects [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 2 years ago.
I have next array:
let someArr = [
{param:{name: 'bla'}},
{param:{name: 'blu'}}
];
how I can get array without 'param'?
[{name: 'bla'},{name: 'blu'}]
let someArr = [
{param:{name: 'bla'}},
{param:{name: 'blu'}}
];
const result = someArr.map(el => el.param);
console.log(result);
let newArray = someArr.map(item => {
return item.param;
});

Replacing for loop in javascript [duplicate]

This question already has an answer here:
JS : Convert Array of Strings to Array of Objects
(1 answer)
Closed 3 years ago.
I am trying to add id in a components array. id's will be incrementing based on the no. of components.
component_names = ['test1', 'test2'];
I want to create a new array components which will become :
components = [{id:1, name: 'test1'}, {id:2, name: 'test2'}]
// The ids will increment as the no. of components increase.
What I am trying:
let arr=[];
for(let i=0;i<component_names.length;i++){
arr.push({id:i+1, name: component_names[i]});
}
The above solution works but can I do the same with any of the higher order functions in javascript?
A simple map will work, where parameter 1 is the item and parameter 2 is the index.
let component_names = ['test1', 'test2']
let result = component_names.map((itm, idx) => ({id:++idx,name:itm}))
console.log(result)
let arr = component_names.map((name, index) => ({ name: name, id: index + 1 }));

How to change the values repeatedly accurs in Array object [duplicate]

This question already has answers here:
Appending the count to duplicates in a javascript string array
(3 answers)
Closed 3 years ago.
Input:-
Here i'm having array object in which natraj is repeating so i need to append some count like given example.
var aa= [
{name:'natraj'},
{name:'ajai'},
{name:'natraj'},
{name:'ajai'},
{name:'barath'},
{name:'ajai'},
{name:'barath'},
{name:'natraj'},
]
output:-
[
{name:'natraj'},
{name:'ajai'},
{name:'natraj_1'},
{name:'ajai_1'},
{name:'barath'},
{name:'ajai_2'},
{name:'barath_1'},
{name:'natraj_2'},
]
Keep a running count:
var aa = [{name:'natraj'},{name:'ajai'},{name:'natraj'},{name:'ajai'},{name:'barath'},{name:'ajai'},{name:'barath'},{name:'natraj'},]
let counts = {}
aa.forEach(o => {
if (counts[o.name]) {
o.name += `_${counts[o.name]++}`
} else {
counts[o.name] = 1
}
});
console.log(aa)

In javascript, how to convert string array into array of object? [duplicate]

This question already has answers here:
Convert an array to an array of objects
(4 answers)
Closed 4 years ago.
I have the following array of string that needs to be turn into array of object with the keys value and label
languages: ["Arabic", "Irish"]
0:"Arabic"
1:"Irish"
length: 2
If I wanted to make this array into an array of object like the following:
languages = [
{ value: 'Arabic', label: 'Arabic' }
{ value: 'Irish', label: 'Irish' }
]
How will I do that? Can someone please help?
You can use Array.map():
var languages = ["Arabic", "Irish"];
var res = languages.map(item => ({'value':item, 'label':item}));
console.log(res);
You can also use Array.forEach() as:
var languages = ["Arabic", "Irish"];
var res = [];
languages.forEach(item => res.push({'value':item, 'label':item}));
console.log(res);

Javascript reposition array items [duplicate]

This question already has answers here:
Sort an array based on another array of integers
(7 answers)
Closed 7 years ago.
I have an array or numbers and objects (same length):
var a = [2,0,1], b = [obj1,obj2,obj3];
I would like to reposition items in array 'b' to the position of numbers in array 'a'.
Could be done with jquery as well.
How can I do that most easily?
Thanks
To do this there is no an auto function but you can use array map to get this result.
var orderByArray = function(order, data) {
return order.map(function(pos) {
return data[pos];
});
};
var a = [2,0,1];
var b = ['obj1', 'obj2', 'obj3'];
var result = orderByArray(a, b);
console.log('result', result);

Categories