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]
}
Related
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);
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;
}
My code looks like this
var res = [];
var temp = [];
function Permutations(target, size) {
if (size === 0) {
res.push(temp);
console.log(res);
return;
}
for (let i = 0; i < target.length; i++) {
if (target[i] !== null) {
temp.push(target[i]);
target[i] = null;
Permutations(target, size - 1);
target[i] = temp.pop();
}
}
}
Permutations([1, 2, 3], 2);
console.log(res);
When I run my code, I can see my res stores each permutation as it is is being executed. However, when I log it outside the function, all the stored value disappeared.
[ [ 1, 2 ] ]
[ [ 1, 3 ], [ 1, 3 ] ]
[ [ 2, 1 ], [ 2, 1 ], [ 2, 1 ] ]
[ [ 2, 3 ], [ 2, 3 ], [ 2, 3 ], [ 2, 3 ] ]
[ [ 3, 1 ], [ 3, 1 ], [ 3, 1 ], [ 3, 1 ], [ 3, 1 ] ]
[ [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ], [ 3, 2 ] ]
[ [], [], [], [], [], [] ] // This is my console.log outside the function
The array temp holds is the same array throughout the complete execution of your code. And res.push(temp); adds this same array (not a copy of it) to your res array.
Here a related question about how Objects are handled in JavaScript: Is JavaScript a pass-by-reference or pass-by-value language?
So your code results in res having N times the same array.
You could copy the element stored in temp to a new array using [...temp], and push that to your res array.
var res = [];
var temp = [];
function Permutations(target, size) {
if (size === 0) {
res.push([...temp]);
return;
}
for (let i = 0; i < target.length; i++) {
if (target[i] !== null) {
temp.push(target[i]);
target[i] = null;
Permutations(target, size - 1);
target[i] = temp.pop();
}
}
}
Permutations([1, 2, 3], 2);
console.log(res);
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' }
// ]
Items in an array can be arranged in ascending order using sort() method in JavaScript but how to arrange them in all possible ways and show them in our web page.
You describe permutations, one way to implement it:
function permutations(arr, r=[]) {
if (arr.length === 0) {
console.log(r)
} else {
const first = arr[0]
for (let i = 0; i <= r.length; i++) {
permutations(arr.slice(1), r.slice(0, i).concat([first]).concat(r.slice(i)))
}
}
}
permutations([1, 2, 3])
OUTPUT
[ 3, 2, 1 ]
[ 2, 3, 1 ]
[ 2, 1, 3 ]
[ 3, 1, 2 ]
[ 1, 3, 2 ]
[ 1, 2, 3 ]