I have something like this:
data = [
{
DateMeasured:"2018-08-27T04:46:25",
Steps:100
},
{
DateMeasured:"2018-08-27T04:46:25",
Steps:500
},
{
DateMeasured:"2018-08-27T04:46:25",
Steps:800
},
{
DateMeasured:"2018-08-26T04:46:25",
Steps:400
},
{
DateMeasured:"2018-08-26T04:46:25",
Steps:300
},
{
DateMeasured:"2018-08-25T04:46:25",
Steps:100
}
];
I have an object of data like above, now I want to recreate object with discrict dates but its highest steps, but now i want like this:
data = [
{
DateMeasured:"2018-08-27T04:46:25",
Steps:800
},
{
DateMeasured:"2018-08-26T04:46:25",
Steps:400
},
{
DateMeasured:"2018-08-25T04:46:25",
Steps:100
}
];
How can I achieve this goal?
You could reduce the array by checking the last inserted object with the same date and if not found, insert the object, otherwise check the value and update the array with a greater Step property.
var data = [{ DateMeasured: "2018-08-27T04:46:25", Steps: 100 }, { DateMeasured: "2018-08-27T04:46:25", Steps: 500 }, { DateMeasured: "2018-08-27T04:46:25", Steps: 800 }, { DateMeasured: "2018-08-26T04:46:25", Steps: 400 }, { DateMeasured: "2018-08-26T04:46:25", Steps: 300 }, { DateMeasured: "2018-08-25T04:46:25", Steps: 100 }],
result = data.reduce((r, o) => {
var index = r.findIndex(({ DateMeasured }) => DateMeasured === o.DateMeasured);
if (index === -1) {
r.push(o);
return r;
}
if (r[index].Steps < o.Steps) {
r[index] = o;
}
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you need to sort by the number of steps and take the first 3 elements:
const data = [ { DateMeasured:"2018-08-27T04:46:25", Steps:100 }, { DateMeasured:"2018-08-27T04:46:25", Steps:500 }, { DateMeasured:"2018-08-27T04:46:25", Steps:800 }, { DateMeasured:"2018-08-26T04:46:25", Steps:400 }, { DateMeasured:"2018-08-26T04:46:25", Steps:300 }, { DateMeasured:"2018-08-25T04:46:25", Steps:100 } ];
const sorted = data.sort((a, b) => b.Steps - a.Steps)
const takeFirst3 = sorted.slice(0, 3)
console.log(takeFirst3)
Related
I am trying to generate tree structure data, the problem is in helper function where I have an empty array children in which I want to push object with data, but get undefined
I do not get undefined when test it separately.
let b = {x: 1}
let a = []
a.push(b)
console.log(a)
function forestMockDataGenerator(n, m) {
const chance = new Chance(Math.random());
const mock = Array.from(Array(n).keys());
return mock.map(function (tree) {
tree = {
datum: chance.name(),
children: [],
};
return helper(tree, 1);
function helper(mock, count) {
if (isCountNotEqualToM(count, m)) {
mock.children.push({
datum: equalOneAddressEqualTwoPhone(count),
children: [],
});
helper(mock.children, (count = count + 1));
}
function equalOneAddressEqualTwoPhone(count) {
return count === 1 ? chance.address() : chance.phone();
}
function isCountNotEqualToM(count, m) {
return count !== m ? true : false;
}
return mock;
}
});
}
example 1
example 2
the data should have the next format
[
{
"name": "String",
"children": [
{
"name": "String",
"children": [
// ...
]
}, {
"name": "String",
"children": [
// ...
]
},
// ...
]
}, {
"name": "String",
"children": [
// ...
]
},
// ...
]
You yould use independent creation of children by handing over the decremented depth.
function forestMockDataGenerator(n, m) {
if (!m) return [];
return Array.from({ length: n }, (_, i) => ({
name: `name${i}`,
children: forestMockDataGenerator(n, m - 1),
}));
}
console.log(forestMockDataGenerator(5, 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }
my backend service send me list of node as an array. but I need is, each next node is value of its previous node(SEE EXAMPLE). I want whole list as nested object in singe object.
WHAT I HAVE:
[
{
"nodeId": 1,
},
{
"nodeId": 3,
},
{
"nodeId": 16,
}
]
WHAT I NEED:
[
{
"nodeId": 1,
"staticChild": [
{
"nodeId": 3,
"staticChild": [
{
"nodeId": 16,
}
]
}
]
}
]
You could reduce the array from the right side and build a new object with a staticChild property.
var array = [{ nodeId: 1 }, { nodeId: 3 }, { nodeId: 16 }],
result = array.reduceRight((a, b) => ({ ...b, staticChild: [a] }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Based on the input / output you provided, you can use a recursive funtion like :
const data = [{
nodeId: 1
},
{
nodeId: 3
},
{
nodeId: 16
}
];
const transform = data => {
const [node, ...rest] = data;
if (rest.length > 0) {
return {
...node,
staticChild: [transform(rest)]
};
} else {
return {
...node,
hasChildren: false
};
}
};
const result = transform(data);
console.log(result);
At first reverse the array and the make an iteration over the revered array using reduce() to make your desire format.
let data = [{"nodeId": 1},{"nodeId": 3},{"nodeId": 16}]
data = data.reverse().reduce((old, cur) => {
if (!old.length) {
old = [cur]
} else {
cur['staticChild'] = old
old = [cur]
}
return old
}, [])
console.log(data)
You can use the reduceRight() array method to perform the transformation.
const data = [{
"nodeId": 1,
},
{
"nodeId": 3,
},
{
"nodeId": 16,
}
]
const nested = data.reduceRight((acc, item) => {
return [ { ...item, staticChild: acc } ]
}, []);
console.log(nested);
Or more succinctly:
const nested = data.reduceRight((acc, item) => [ { ...item, staticChild: acc } ],[]);
I have this following array
var array=[{ semster:1, name:Book1 }, { semster:1, name:Book2 }, { semster:2, name:Book4 }, { semster:3, name:Book5 }, { semster:3, name:Book6 }, { semster:4, name:Book7 }]
Now I want to sort my array to split the current array into chunks of array like following
var array=[[{ semster:1, name:Book1 }, { semster:1, name:Book2 }],[ { semster:2, name:Book4 }], [{ semster:3, name:Book5 }, { semster:3, name:Book6 }], [{ semster:4, name:Book7 }]]
I have tried to achieve this with following code :
function splitIntoSubArray(arr, count) {
var newArray = [];
while (arr.length > 0) {
newArray.push(arr.splice(0, count));
}
return newArray;
}
But this can only divide the array on the basis of fixed size. Any kind of suggestion is appreciated.
Thanks
You can simply use Array.reduce() to group items by semester. Object.values() on the map gives you the desired result.
var array=[{ semster:1, name:"Book1" }, { semster:1, name:"Book2" }, { semster:2, name:"Book4" }, { semster:3, name:"Book5" }, { semster:3, name:"Book6" }, { semster:4, name:"Book7" }];
var result = Object.values(array.reduce((a, curr)=>{
(a[curr.semster] = a[curr.semster] || []).push(curr);
return a;
},{}));
console.log(result);
You could reduce the array by checking the last group with the same semester.
var array = [{ semester: 1, name: 'Book1' }, { semester: 1, name: 'Book2' }, { semester: 2, name: 'Book4' }, { semester: 3, name: 'Book5' }, { semester: 3, name: 'Book6' }, { semester: 4, name: 'Book7' }],
grouped = array.reduce((r, o) => {
var last = r[r.length - 1];
if (last && last[0].semester === o.semester) {
last.push(o);
} else {
r.push([o]);
}
return r;
}, []);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I am trying to create an object from a forEach loop in javascript and in this simple object, I am trying to add up all of the counts for each item in the array.
Currently, I'm using firebase in an ionic (angular/typescript) project and I am returning an array of items from firebase. The array looks something like this:
[
{
id:'uniqueID',
specs: {
count:5,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Foxeer Cam 2",
type:"camera"
}
},
{
id:'uniqueID',
specs: {
count:4,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Furibee 40a",
type:"esc"
}
},
{
id:'uniqueID',
specs: {
count:4,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Runcam Cam 1",
type:"camera"
}
},
{
id:'uniqueID',
specs: {
count:1,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Hobbywing 4 in 1",
type:"esc"
}
}
]
Here's how I'm running through these items (result being the list of items):
let partArr = [];
let typeObj = {};
result.forEach(part => {
//Put all parts in a list
partArr.push({
'id':part.id,
'specs':part.data(),
});
//Put all types in a list
typeObj[part.data().type] = {
'count': 0
};
});
Now, I need to increment the count, adding each part's count to the last depending on their type. The typeObj should look something like this.
{
esc: {
count:5
},
camera: {
count:10
}
}
I tried adding the count to the count like so:
typeObj[part.data().type] = {
'count': typeObj[part.data().type].count + part.data().count
};
but it does not recognize there being a count when I'm first making the object. (I think).
Any advice?
You can use Array#reduce to accomplish this since you want to transform an array into a single object:
const array = [
{
id: 'uniqueID',
specs: {
count: 5,
forSale: false,
group: "qPELnTnwGJEtJexgP2qX",
name: "Foxeer Cam 2",
type: "camera"
}
},
{
id: 'uniqueID',
specs: {
count: 4,
forSale: false,
group: "qPELnTnwGJEtJexgP2qX",
name: "Furibee 40a",
type: "esc"
}
},
{
id: 'uniqueID',
specs: {
count: 4,
forSale: false,
group: "qPELnTnwGJEtJexgP2qX",
name: "Runcam Cam 1",
type: "camera"
}
},
{
id: 'uniqueID',
specs: {
count: 1,
forSale: false,
group: "qPELnTnwGJEtJexgP2qX",
name: "Hobbywing 4 in 1",
type: "esc"
}
}
];
const typeObj = array.reduce((obj, { specs: { count, type } }) => {
obj[type] = obj[type] || { count: 0 };
obj[type].count += count;
return obj;
}, {});
console.log(typeObj);
What this does is assign obj[type] to either itself or if it doesn't yet exist, a new object { count: 0 }. Then it increments the count property of obj[type] by the specified count in the data.
If you have a data method that returns an object with the data (as you seem to have in the question), you can modify it like so:
const typeObj = array.reduce((obj, item) => {
const { type, count } = item.data().specs;
obj[type] = obj[type] || { count: 0 };
obj[type].count += count;
return obj;
}, {});
console.log(typeObj);
It would probably be easier to use reduce to generate the object with the counts all at once, and to call .data() only once on each iteration:
const results = [
{
data() { return { specs: {
count:5,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Foxeer Cam 2",
type:"camera"
}}}},
{
data() { return { specs: {
count:4,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Furibee 40a",
type:"esc"
}}}},
{
data() { return { specs: {
count:4,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Runcam Cam 1",
type:"camera"
}}}},
{
data() { return { specs: {
count:1,
forSale:false,
group:"qPELnTnwGJEtJexgP2qX",
name:"Hobbywing 4 in 1",
type:"esc"
}}}}
];
const typeObj = results.reduce((a, item) => {
const { count, type } = item.data().specs;
if (!a[type]) a[type] = { count: 0 };
a[type].count += count;
return a;
}, {});
console.log(typeObj);
I figure I shouldn't be having trouble with this, but I am. I am trying to switch up the syntax/variables of a JSON object to match a certain parameters.
Here is the JSON I am working with:
{
"name":"BHPhotovideo",
"prices":[
{
"price":"799.00",
"createdAt":"2017-07-23T16:17:11.000Z",
"updatedAt":"2017-07-23T17:21:41.000Z"
},
{
"price":"770.00",
"createdAt":"2017-07-21T16:17:11.000Z",
"updatedAt":"2017-07-23T16:17:11.000Z"
},
{
"price":"599.00",
"createdAt":"2017-07-19T16:17:11.000Z",
"updatedAt":"2017-07-22T16:17:11.000Z"
},
{
"price":"920.00",
"createdAt":"2017-07-22T16:17:11.000Z",
"updatedAt":"2017-07-22T16:17:11.000Z"
}
]
},
etc...
I am just trying to get the data to be formatted like this:
{
"label":"BHPhotoVideo", // Same as name
"data":[
{
"x":"2017-07-23T16:17:11.000Z", // Same as createdAt
"y":799 // Same as price
},
{
"x":"2017-07-21T16:17:11.000Z",
"y":770
},
{
"x":"2017-07-19T16:17:11.000Z",
"y":599
},
{
"x":"2017-07-22T16:17:11.000Z",
"y":920
}
]
},
etc...
The amount of these objects are dynamic/subject to change, I've been making a mess out of foreach loops and trying to piece this together. I keep coming into errors, what's the best way to approach this?
What about this ?
data.map(
(item) => ({
"label":"BHPhotoVideo", // Same as name
"data": item.prices.map(nested => ( {
"x":nested.createdAt,
"y":nested.price
}))
})
)
Did you want the y values to be integers?
var ar = [
{
"name":"BHPhotovideo",
"prices":[
{
"price":"799.00",
"createdAt":"2017-07-23T16:17:11.000Z",
"updatedAt":"2017-07-23T17:21:41.000Z"
},
{
"price":"770.00",
"createdAt":"2017-07-21T16:17:11.000Z",
"updatedAt":"2017-07-23T16:17:11.000Z"
},
{
"price":"599.00",
"createdAt":"2017-07-19T16:17:11.000Z",
"updatedAt":"2017-07-22T16:17:11.000Z"
},
{
"price":"920.00",
"createdAt":"2017-07-22T16:17:11.000Z",
"updatedAt":"2017-07-22T16:17:11.000Z"
}
]
},
{
"name":"Adorama",
"prices":[
{
"price":"799.00",
"createdAt":"2017-07-22T16:17:11.000Z",
"updatedAt":"2017-07-23T17:21:41.000Z"
},
{
"price":"799.00",
"createdAt":"2017-07-20T16:17:11.000Z",
"updatedAt":"2017-07-23T16:17:11.000Z"
},
{
"price":"810.00",
"createdAt":"2017-07-18T16:17:11.000Z",
"updatedAt":"2017-07-22T16:17:11.000Z"
},
{
"price":"799.00",
"createdAt":"2017-07-17T16:17:11.000Z",
"updatedAt":"2017-07-22T16:17:11.000Z"
}
]
}
];
var out = ar.map( function(a) {
return {
"label" : a.name,
"prices" : a.prices.map( function(aa) { return {x: aa.createdAt, y: aa.price} })
}
});
console.log( out );
map over the original array returning a changed object; returning the name, and a new array from using map over the prices.
const obj2 = obj.map((item) => {
return {
label: item.name,
data: item.prices.map((data) => {
return {
x: data.createdAt,
y: data.price
}
})
}
});
DEMO