This question already has answers here:
How can I group an array of objects by key?
(32 answers)
Most efficient method to groupby on an array of objects
(58 answers)
Group array items using object
(19 answers)
Closed 2 years ago.
Im building a function on Javascript to reduce an array like this:
var myArray = [
{sku: "one", price: "3"},
{sku: "two", price: "5"},
{sku: "one", price: "2"},
{sku: "three", price: "3"},
{sku: "three", price: "9"}
];
to this:
{ one: [ '3', '2' ], two: [ '5' ], three: [ '3', '9' ] }
in order to categorize my skus. It works just fine right now.
function itemQuantity(data) {
let group_to_values = data.reduce(function (obj, item) {
obj[item.sku] = obj[item.sku] || [];
obj[item.sku].push(item.price);
return obj;
}, {});
return group_to_values;
}
console.log(itemQuantity(myArray));
My issue comes when I try to modify it. instead of having one: [ '3', '2' ] I need the NUMBER of items (or quantity) {one: 2, two: 1...} I trieed to add obj.length but cant make it work!
Please help!
Related
This question already has answers here:
Merge/flatten an array of arrays
(84 answers)
Closed 1 year ago.
const arr1 = [
[{ id: 1 }],
[{ id: 2 },{ id: 3 }],
[{ id: 4 }]
];
I want to add all items in this array how can I do this. I want my output as Like:
const arr2 = [
{id:1},
{id:2},
{id:3},
{id:4}
]
Using arr1.flat() will work for your example. If you have an array of even greater depth of nested arrays of objects, you can even use arr1.flat(Infinity) to flatten to a variable depth:
const arr1 = [
{ id: 0 },
[{ id: 1 }],
[{ id: 2 },{ id: 3 }],
[{ id: 4 }]
];
console.log(arr1.flat());
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Given two arrays of the same length and identical content, how can one sort an array to be the in same order as the second array, based on a shared property?
Example:
let array1 = [{id: 123, ...}, {id: 456, ...}, {id: 789, ...}] // order always stays the same
let array2 = [{id: 456, ...}, {id: 789, ...}, {id: 123, ...}] // order is always different
How can I sort array1 such that:
array1[0].id is 456 and
array2[0].id is 456
Loop through the first and push to the second by index:
let arr1 = [{id: 123}, {id: 456}, {id: 789}] // order always stays the same
let arr2 = [{id: 456}, {id: 789}, {id: 123}]
arr1.forEach((obj1, idx) => {
arr2[idx] = obj1
})
console.log(arr1, arr2)
Assuming array2 has the objects we care about and array1 specifies the order, map over the ordering array using it to select the objects to be ordered...
let array1 = [{id: 123 }, {id: 456 }, {id: 789, }]
let array2 = [{id: 456, name: '456' }, {id: 789, name: '789' }, {id: 123, name: '123' }]
let array2ElementsSortedByArray1 = array1.map(e => {
return array2.find(e2 => e2.id === e.id)
})
console.log(array2ElementsSortedByArray1)
You can create a hash of the shape {id: index, ...} from array2 and then use this to order the elements of array1. This saves you the cost of find() on each iteration.
let array1 = [{ id: 123, }, { id: 456, }, { id: 789, }] // order always stays the same
let array2 = [{ id: 456, }, { id: 789, }, { id: 123, }]
const
indeces = Object.fromEntries(array2.map(({ id }, i) => [id, i])), // { 456: 0, 789: 1, 123: 2 }
ordered = [];
array1.forEach(o => ordered[indeces[o.id]] = { ...o });
console.log(ordered)
This question already has answers here:
Sum JavaScript object propertyA values with the same object propertyB in an array of objects
(12 answers)
Group by, and sum, and generate an object for each array in JavaScript
(4 answers)
JavaScript SUM and GROUP BY of JSON data
(5 answers)
How to group by and sum an array of objects? [duplicate]
(2 answers)
Closed 3 years ago.
I have the following array like this
[
{name: "calpol", quantity: 12},
{name: "paracetamol", quantity: 15},
{name: "paracetamol", quantity: 10},
]
and I want to sum up the quantity when the product is the same so i can get an array like :
[
{name: "calpol", quantity: 12},
{name: "paracetamol", quantity: 25},
]
Use reduce and in the accumulator array check if there exist a object with a name such as calpol or paracetamol. If it exist then update the quantity else create new object and push it in the accumulator
let prod = [{
name: "calpol",
quantity: 12
},
{
name: "paracetamol",
quantity: 15
},
{
name: "paracetamol",
quantity: 10
},
]
let sum = prod.reduce(function(acc, curr) {
let findIndex = acc.findIndex(item => item.name === curr.name);
if (findIndex === -1) {
acc.push(curr)
} else {
acc[findIndex].quantity += curr.quantity
}
return acc;
}, [])
console.log(sum)
This question already has answers here:
How to insert an item into an array at a specific index (JavaScript)
(28 answers)
Closed 3 years ago.
I already see the lodash documentation but I don't know what function do I need to use to solve my problem. I have array
const arr = [
{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
]
I want to add {name: 'ace'} before saske. I know about splice in javascript, but I want to know if this is possible in lodash.
Currently lodash not have that. You can use this alternate
arr.splice(index, 0, item);
const arr = [
{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
]
arr.splice(2, 0, {name: 'ace'})
console.log(arr)
You can try something like this:
const arr = [{
name: 'john'
},
{
name: 'jane'
},
{
name: 'saske'
},
{
name: 'jake'
},
{
name: 'baki'
}
]
const insert = (arr, index, newItem) => [
...arr.slice(0, index),
newItem,
...arr.slice(index)
];
const newArr = insert(arr, 2, {
name: 'ace'
});
console.log(newArr);
There is no support of such functionality in lodash : see issue.
If you still want it to look like done with lodash, then you can do it like this way.
fields = [{name: 'john'},
{name: 'jane'},
{name: 'saske'},
{name: 'jake'},
{name: 'baki'}
];
_.insert = function (arr, index, item) {
arr.splice(index, 0, item);
};
_.insert(fields,2,{'name':'ace'});
console.log(fields);
I'm using lodash to group an array of objects:
let people = [
{name:'carl',group:'one'},
{name:'john',group:'one'},
{name:'dean',group:'three'}
]
_.groupBy(people,"group");
Result:
one: Array (2 items)
0: Object {group: "one", name: "carl"}
1: Object {group: "one", name: "john"}
three: Array (1 item)
0: Object {group: "three", name: "dean"}
What I want is the objects with group array length higher than 1 to separate into another array individually like this:
one: Array (1 item)
0: Object {group: "one", name: "carl"}
one: Array (1 item)
0: Object {group: "one", name: "john"}
three: Array (1 item)
0: Object {group: "three", name: "dean"}
What is the best way to do that?
I think you can use the method "sort"
let people = [{name:'carl',group:'one'},
{name:'john',group:'one'},
{name:'dean',group:'three'}];
people.sort(function(a,b){
return a.name.localeCompare(b.name)
});
Reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort