I have below const
const cartProducts = props.cartSlice;
whose output is below array
Array [
Object {
"cartQuantity": 3,
"product": "5f15d92ee520d44421ed8e9b",
},
Object {
"cartQuantity": 2,
"product": "5f15d964e520d44421ed8e9c",
},
Object {
"cartQuantity": 1,
"product": "62e5285f92b4fde9dc8a384c",
},
Object {
"cartQuantity": 4,
"product": "5f15d9b3e520d44421ed8e9d",
},
]
I am trying to write some code in reactjs to output separate arrays with the only the cartQuantity
as below
Array [
3,
]
Array[
2,
]
Array[
1,
]
Array[
4,
]
The closest I have come to achieving this is below which is consolidating all the cartQuantity in a single array.
const quantity = cartProducts.map((item, i) => item.cartQuantity);
Array [
3,
2,
1,
4,
]
How can I modify my query to output separate arrays for each cartQuantity?
You already mapped the initial array into an array of quantities, now if you want to get an array of arrays, with one quantity into each inner array, then it suffices to make the map callback return an Array with such quantity.
const quantity = cartProducts.map((item, i) => [item.cartQuantity]);
Array [
Array [
3
],
Array[
2
],
Array[
1
],
Array[
4
]
]
i may not have understood your question properly, but would
const quantity = cartProducts.map((item, i) => [ item.cartQuantity ]);
not do?
var cartProducts=[
{
"cartQuantity": 3,
"product": "5f15d92ee520d44421ed8e9b",
},
{
"cartQuantity": 2,
"product": "5f15d964e520d44421ed8e9c",
},
{
"cartQuantity": 1,
"product": "62e5285f92b4fde9dc8a384c",
},
{
"cartQuantity": 4,
"product": "5f15d9b3e520d44421ed8e9d",
},
]
const quantity = cartProducts.map((item, i) => [item.cartQuantity]);
console.log(quantity);
Related
I have one array of object which looks something like this:-
const myObjArr = [
{
"channelName": "AFM",
"21-Apr-2022": 2,
"22-Apr-2022": 2,
"27-Apr-2022": 1,
"29-Apr-2022": 3,
"19-Apr-2022": 1
},
{
"channelName": "Organic Others",
"6-Apr-2022": 6,
"27-Apr-2022": 4,
"7-Apr-2022": 3,
"21-Apr-2022": 1,
"8-Apr-2022": 1
},
{
"channelName": "website",
"27-Apr-2022": 1
}
]
now I want to add one more key, which is named as total in each object of this array which hold sum of all date keys to clarify I am providing the required output in the reqArray variable below
reqArray = [
{
"channelName": "AFM",
"21-Apr-2022": 2,
"22-Apr-2022": 2,
"27-Apr-2022": 1,
"29-Apr-2022": 3,
"19-Apr-2022": 1,
"total":9
},
{
"channelName": "Organic Others",
"6-Apr-2022": 6,
"27-Apr-2022": 4,
"7-Apr-2022": 3,
"21-Apr-2022": 1,
"8-Apr-2022": 1
"total": 15
},
{
"channelName": "website",
"27-Apr-2022": 1,
"total" : 1
}
]
function addFieldsForItem (arr = []) {
arr.forEach(function(item) {
let total = 0;
Object.keys(item).forEach(function(key) {
if (typeof item[key] === 'number') {
total = total + item[key]
}
})
item.total = total
})
return arr;
}
I have this array which holds objects;
let arr = [
{
"id": 1,
"level": "2",
},
{
"id": 2,
"level": "3",
}
]
By default the array has keys starting from 0 and it looks like this:
[
0: {id: 1, level:2},
1: {id: 2, level:3}
]
How can I transform it so that the keys are the values of the property 'level'?
It should look like this:
[
2: {id:1, level:2},
3: {id:1, level:3}
]
So far I have tried this but it doesn't remove the original keys:
arr.map((v, k) => ({[v.level]: v}));
So I have something like this:
[
0: {2:
{id: 1, level:2}
},
1: {3:
{id: 2, level:3}
}
]
You need to populate a new array using reduce:
arr.reduce((prev, curr) => { prev[curr.level] = curr; return prev }, [])
I think I prefer the reduce method, but you could also construct an "array-like" (i.e. an object with numeric keys and a length property) and pass it to Array.from
const maxIdx = Math.max(...arr.map(v => parseInt(v.level, 10)))
const arrLen = maxIdx + 1;
const arrayLike = {
...Object.fromEntries(arr.map(v => [v.level, v])),
length: arrLen
};
const mappedArray = Array.from(arrayLike);
For output of
[undefined, undefined, {
"id": 1,
"level": "2"
}, {
"id": 2,
"level": "3"
}]
Json 1
{
"ordering_data": [
{
"order": 0,
"section_menu_id": 3
},
{
"order": 1,
"section_menu_id": 1
},
{
"order": 2,
"section_menu_id": 6
},
]
}
Json 2
[
3,
7,
4,
]
Expected result
{
"ordering_data": [
{
"order": 3,
"section_menu_id": 3
},
{
"order": 7,
"section_menu_id": 1
},
{
"order": 4,
"section_menu_id": 6
},
]
}
I got 2 json files. can someone tell me how to change the data structure to expected result .I have tried map but it kinda confused for me. Need some help .Thanks in advance.
You can use Array.prototype.map to accomplish this.
On Array.map, through the reference, the second param represents the current index of the array so based on that value, you can assign second array value to order key by index.
const input1 = {
"ordering_data": [
{
"order": 0,
"section_menu_id": 3
},
{
"order": 1,
"section_menu_id": 1
},
{
"order": 2,
"section_menu_id": 6
},
]
};
const input2 = [
3,
7,
4,
];
const updatedOrderingData = input1.ordering_data.map((item, index) => ({
...item,
order: input2[index]
}));
const result = {
ordering_data: updatedOrderingData
};
console.log(result);
I think you are looking for something like the below code snippet.
This assumes that both objects are of equal length, and we are modifying the original object.
First, loop the array, and replace the order in the original object with the numbers in the array.
Make it an exercise to create a new object instead of modifying the original obj1
var obj1 = {
"ordering_data": [
{
"order": 0,
"section_menu_id": 3
},
{
"order": 1,
"section_menu_id": 1
},
{
"order": 2,
"section_menu_id": 6
},
]
};
var myArray = [
3,
7,
4,
];
for(var i = 0; i<myArray.length; i++){
obj1.ordering_data[i].order = myArray[i];
}
console.log(obj1);
This might help.
j1 = {
"ordering_data": [
{
"order": 0,
"section_menu_id": 3
},
{
"order": 1,
"section_menu_id": 1
},
{
"order": 2,
"section_menu_id": 6
},
]
};
j2 = [
3,
7,
4,
]
for(i=0; i<j1.ordering_data.length; i++ ){
j1.ordering_data[i].order = j2[i]
}
I am trying to sort the time. but I am unable to sort by time (hh:mm:ss) format. so i have used moments js. my array sort by time not get sorted. how sort array by using maps
I have an array of objects:
let elements =[
{
"id": 1,
"date": "02:01:02"
},
{
"id": 2,
"date": "01:01:01"
},
{
"id": 3,
"date": "03:01:01"
},
{
"id": 4,
"date": "04:01:01"
}
];
let parsedDates = new Map(
elements.map(e =>[["id", "date"],[e.id, moment(e.date, 'hh:mm:ss')]])
);
elements.sort((a, b) => parsedDates.get(a) - parsedDates.get(b));
console.log(elements.map(e => ({ id: e.id, date: e.date })));
You can lexicographical sort the time using string.localeCompare().
let times = [ { "id": 1, "date": "02:01:02" }, { "id": 2, "date": "01:01:01" }, { "id": 3, "date": "03:01:01" }, { "id": 4, "date": "04:01:01" } ];
times.sort((a,b) => a.date.localeCompare(b.date));
console.log(times);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can try this
function convertDateObj(hhmmss){
let obj = new Date();//creates a Date Object using the clients current time
let [hours,minutes,seconds] = hhmmss.split(':');
obj.setHours(+hours); // set the hours, using implicit type coercion
obj.setMinutes(minutes); //you can pass Number or String, it doesn't really matter
obj.setSeconds(seconds);
return obj;
}
let elements =[
{
"id": 1,
"date": "02:01:02"
},
{
"id": 2,
"date": "01:01:01"
},
{
"id": 3,
"date": "03:01:01"
},
{
"id": 4,
"date": "04:01:01"
}
];
elements.sort((a, b) => convertDateObj(a.date) - convertDateObj(b.date)); // Ascending order
elements.sort((a, b) => convertDateObj(b.date) - convertDateObj(a.date)); // Descending order
The parsedDates map you've created is looking like:
Map {
[ 'id', 'date' ] => [ 1, <some Date object> ],
[ 'id', 'date' ] => [ 2, <some Date object> ],
[ 'id', 'date' ] => [ 3, <some Date object> ],
[ 'id', 'date' ] => [ 4, <some Date object> ]
}
And then you try to extract from it with elements like this:
parsedDates.get({ "id": 1, "date": "02:01:02" })
This should not work, because the key in a Map is and Array instance.
Even if you were using an array as a key:
parsedDates.get([ 1, "02:01:02" ])
this still wouldn't work, as this would be a different Object reference. I mean two arrays
a = [ 1, "02:01:02" ]
b = [ 1, "02:01:02" ]
are stored in different places and are different Objects, even though their values are identical.
So, you can modify your solution a bit:
let elements =[
{
"id": 1,
"date": "02:01:02"
},
{
"id": 2,
"date": "01:01:01"
},
{
"id": 3,
"date": "03:01:01"
},
{
"id": 4,
"date": "04:01:01"
}
];
let parsedDates = new Map(
elements.map(e => [e.date, e])
);
elements = elements.map(x => x.date).sort().map(x => parsedDates.get(x))
console.log(elements)
// [
// { id: 2, date: '01:01:01' },
// { id: 1, date: '02:01:02' },
// { id: 3, date: '03:01:01' },
// { id: 4, date: '04:01:01' }
// ]
array1 = [{
"id": 1,
"name": "aaa",
},
{
"id": 2,
"name": "bbb"
},
{
"id": 5,
"name": "ccc"
},
{
"id": 6,
"name": "ddd"
},
{
"id": 8,
"name": "eee"
},
{
"id": 12,
"name": "fff"
}]
array2 = [ 5, 6, 8 ,12]
Resulting Array = [ {name: "ccc"}, {name: "ddd"} , {name: "eee"}, {name: "fff"} ]
I am looking to map both arrays to get matching id numbers and get copy the names in the resulting arrray but I didn't succeed. Can you please suggest me how to do it?
Thank you
You could try the following. Basically, you're filtering the first array based on whether or not the id exists in the 2nd array and then mapping it back by only selecting the key(s) you want.
var resultArray = array1.filter(function(arr) {
return array2.indexOf(arr.id) !== -1;
}).map(function(item) {
return {
name: item.name
};
});
Let's turn array1 into an object first, that maps ids to the corresponding objects:
var idMap = {}
array1.forEach(function(element) {
idMap[element.id] = element
})
You can then get the result you want by doing
var result = array2.map(function(id) {
return idMap[id]
});
Try This:
array1 = [{"id": 1,"name": "aaa"},{"id": 2,"name": "bbb"},{"id": 5,"name": "ccc"},{"id": 6,"name": "ddd"},{"id": 8,"name": "eee"},{"id": 12,"name": "fff"}] ;
array2 = [ 5, 6, 8 ,12];
var result = array1.filter(item => array2.includes(item.id)).map(({id,name}) => ({name}));
console.log( result );