This question already has answers here:
Sum JavaScript object propertyA values with the same object propertyB in an array of objects
(12 answers)
Closed 5 months ago.
I Want to sum all price values of an array for duplicated elements in array... I have this array:
var products = [["product_1", 6, "hamburger"],["product_2", 10, "cola"],["product_2", 7, "cola"], ["product1", 4, "hamburger"]]
And this is what I want:
var products = [["product_1", 10, "hamburger"],["product_2", 17, "cola"]]
Can any good soul help me?
I think you meant to write ........, ["product_1", 4, "hamburger"]].
You can use Object.values() and Array#reduce methods as in the following demo:
const
products = [
["product_1", 6, "hamburger"],
["product_2", 10, "cola"],
["product_2", 7, "cola"],
["product_1", 4, "hamburger"]
],
output = Object.values(
products.reduce(
(acc, [id, num, name]) =>
({ ...acc,
[id]: [id, (acc[id] && acc[id][1] || 0) + num, name]
}), {}
)
);
console.log(output);
Related
This question already has answers here:
Convert object to array of key–value objects like `{ name: "Apple", value: "0.6" }`
(3 answers)
Closed 1 year ago.
I'm sorry if this is redundant with other posts but I currently have the following array:
let test = {1:100, 2:200, 3:300}
But I'd like to convert this to:
test = [
{id: 1, value: 100},
{id: 2, value: 200},
{id: 3, value: 300}
]
Any help appreciated - even just pointing me to posts that solve this question :)
You can use Object.entries to get an array of key, value pairs and then map that to an array of objects:
let test = {1:100, 2:200, 3:300};
let out = Object.entries(test).map(([k, v]) => ({ id : k, value: v }));
console.log(out);
Here's a version using keys and map:
var obj = {1:100,2:200,3:300}
var result = Object.keys(obj).map((key) => ({ id: key, value: obj[key]}));
console.log(result)
Using Object.entries() and some destructuring
let test = {1:100, 2:200, 3:300}
let res = Object.entries(test).map(([id, value]) => ({id, value}))
console.log(res)
This question already has answers here:
How to produce an array from an object where the number of elements is determined by Object.values?
(7 answers)
Closed 3 years ago.
I have an object with products:
products: {
bread: 1,
milk: 2,
cheese: 2,
chicken: 1,
}
I would like to have an array with the name of products like this:
products: ['bread', 'milk', 'milk', 'cheese', 'cheese', 'chicken']
I was trying to use lodash with reduce method but I don't know how to "multiply" this product in array.
I think this is not a good idea:
_.reduce(products, (result, value, key) => {
for(let i = 0; i < value; i++) {
result.push(key);
}
return result;
}, [])
So if anyone could help, I will be grateful.
You could use flatMap over the entries of the object
const products = {
bread: 1,
milk: 2,
cheese: 2,
chicken: 1,
}
const output = Object.entries(products).flatMap(([k, v]) => Array(v).fill(k))
console.log(output)
With lodash you can iterate the array with _.flatMap(). Create the the callback using _.overArgs() that will pass the value (via _.identity()) and the key (wrapped with _.constant()) to _.times():
const obj = {
products: {
bread: 1,
milk: 2,
cheese: 2,
chicken: 1,
}
}
const result = _.flatMap(obj.products, _.overArgs(_.times, [_.identity, _.constant]))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
i have and array
reservation1:[
{name:"8:30",active:true,dayindex:1},
{name:"jad",active:true,dayindex:3},
]
i need to expand the array to 9
and fill it with object with name null active false dayindex: between 0 and 10 in order
the output needed is
output =[
{name:"",active:false,dayindex:0}
{name:"8:30",active:true,dayindex:1}
...
i tried this for expanding
it worked for expanding but i couldnt reorder it as i wanted
You can sort you array after adding others elements:
var reservation = [
{name:"8:30",active:true,dayindex:1},
{name:"jad",active:true,dayindex:3},
{name:"tony",active:true,dayindex:4},
{name:"",active:false,dayindex:6}
];
var availabeDayIndex = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].filter(el => !reservation.map(it => it.dayindex).includes(el));
var sortField = 'dayindex';
reservation = [...reservation, ...Array.from(Array(9 - reservation.length), (val, key) => ({name: null, active: false, dayindex: availabeDayIndex[key]}))].sort((a, b) => a[sortField] - b[sortField]);
console.log(reservation);
This question already has answers here:
Filter Array of Array for values inside nested array
(4 answers)
Only specific 'columns' from a 2d javascript array
(4 answers)
Closed 4 months ago.
I have these variables:
var arr = [
[ "name1", 2, "filter1" ],
[ "name2", 5, "filter2" ],
[ "name3", 8, "filter3" ],
[ "name4", 1, "filter2" ]
];
// This variable may have values: `"filter1"`, `"filter2"`, `"filter3"`.
var filter = "filter2";
How can I filter the array arr according to the filter variable values?
My example must return this:
[
[ "name2", 5 ],
[ "name4", 1 ]
]
Beside the filtering, you need to get only the first two elements of the inner arrays.
Array#filter returns the same elements in the array. For getting the wanted items without the filter item, you need to return either the first two objects, or filter the items with the given filter as well (proposal 2).
var array = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'], ['name3', 8, 'filter3'], ['name4', 1, 'filter2']],
filter = 'filter2',
result = array.filter(a => a[2] === filter).map(a => a.slice(0, 2));
console.log(result);
var array = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'], ['name3', 8, 'filter3'], ['name4', 1, 'filter2']],
filter = 'filter2',
result = array
.filter(a => a.some(v => v === filter))
.map(a => a.filter(v => v !== filter));
console.log(result);
By using filter method you can easily test what you want and only return the match elements
var arr = [['name1', 2, 'filter1'], ['name2', 5, 'filter2'],['name3', 8, 'filter3'], ['name4', 1, 'filter2']];
var filter = 'filter2';
var result = arr.filter(function(res){
return res[2] == filter;
}).map(function(filtered){
return filtered.slice(0,2);
});
console.log(result);
This question already has answers here:
Changing the key name in an array of objects?
(11 answers)
Closed 5 years ago.
How can I transform values from an array to a new array?
I have an array like:
[
{ "amount" : 10, "date" : "2017-05-30" }...
]
which I want to "transform" into
[
{ x : 10, y: 2017-05-30 }
]
any help is appreciated...
You could map new objects with the new properties.
var array = [{ amount: 10, date: "2017-05-30" }],
newArray = array.map(a => ({ x: a.amount, y: a.date }));
console.log(newArray);
Using Array#map()
The callback function will create a new object with the 2 properties needed. You just have to keep the value of the current array
const array = [{ "amount" : 10, "date" : "2017-05-30" }];
let newArray = array.map(_=>({x:_.amount,y:_.date}));
console.log(newArray);
You can try using lodash map Lodash map
It will be something like:
const array2 = _.map(array1, (item) => { x: item.amount, y: item.date });