I have this array shown in console
(3) [{…}, {…}, {…}]
0: {num3: 1, num2: 1}
1: {num3: 2, num2: 4}
2: {num3: 3, num2: 1}
length: 3
pop: ƒ ()
push: ƒ ()
shift: ƒ ()
splice: ƒ ()
unshift: ƒ ()
_chartjs: {listeners: Array(1)}
__proto__: Array(0)
I just want to change the format to this
(3) [{…}, {…}, {…}]
0: {1, 1}
1: {2, 4}
2: {3, 1}
length: 3
pop: ƒ ()
push: ƒ ()
shift: ƒ ()
splice: ƒ ()
unshift: ƒ ()
_chartjs: {listeners: Array(1)}
__proto__: Array(0)
So then I can use it to draw a scatter chart using chart.js
You can use map function like so.
let newArr = oldArr.map(x => [x.num3, x.num2])
I think you mean to output an array of arrays considering an object must have a key/value. To do so, this function should get the job done.
const formatArr = (arr) => arr.map(({ num1, num2 }) => ([num1, num2]))
You can then use this for multiple charts like so:
const newChart = formatArr(oldChart)
FYI: You should probably rename my function to something more descriptive.
Since you want to remove the name, then you should turn to an object into an array of values.
you cant do this: item = {1,2} but you can do this item = [1,2].
Considering you meant removing the properties which will lead to an array [1,2], Try this:
const arr = [
{num3: 1, num2: 1},
{num3: 2, num2: 4},
{num3: 3, num2: 1}]
const arr2 = arr.map(k => Object.keys(k).map(ok => k[ok]))
console.log({arr2})
Update: Looking at the scatter chart in chart.js you should have an x and a y as props instead, use this:
const arr = [
{num3: 1, num2: 1},
{num3: 2, num2: 4},
{num3: 3, num2: 1}]
// your object should be like this
const data = arr.map(k => ({x: k.num3,y: k.num2}))
console.log(data)
Reference: Scatter Chart - Chart.js
Related
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
convert array of objects into object of objects properties from array
(4 answers)
Closed 12 months ago.
I have a parsed json array:
parsedJson = JSON.parse(comments);
const reformattedArray = parsedJson.map(({username, rating}) => ({[username]: rating}));
[{…}, {…}, {…}, {…}, {…}]
[{First username: 5}, {Second username: 4}, {Third username: 3}, {Fourth username: 2}, {Fifth username: 1}]
but how is it possible to look my array like this:
{…,…,…,…,…}
{First username: 5, Second username: 4, Third username: 3, Fourth username: 2, Fifth username: 1}
Is it possible to make this array to look like this?
You can easily achieve this with Array.reduce:
const data = [{FirstUsername: 5}, {SecondUsername: 4}, {ThirdUsername: 3}, {FourthUsername: 2}, {FifthUsername: 1}]
const oneObject = data.reduce((total, current) => {
const keyName = Object.keys(current)[0]
total[keyName] = current[keyName]
return total
}, {})
console.log(oneObject)
I have a very simple block of code:
function toObj(i){
return {
i: i
};
}
numObj=s=>s.map(toObj)
When I pass an array of numbers to numObj, I expect the key and the value to match the argument that was passed in. For example, I would expect the following result:
numObj([1, 2, 3, 4]) => [{1: 1}, {2: 2}, {3: 3}, {4: 4}]
instead, I get this:
numObj([1, 2, 3, 4]) => [{i: 1}, {i: 2}, {i: 3}, {i: 4}]
How can I set the key of the returned object to be the argument that was passed in?
Use computed property names to create the key from a value:
const toObj = i => ({ [i]: i })
const numObj = arr => arr.map(toObj)
const result = numObj([1, 2, 3, 4])
console.log(result)
I'm struggling with array manipulation when they are arrays of different types. My problem is rather simple, but I would still appreciate any assistance.
I have the following two classes:
export interface Group {
gId: number;
gName: string;
}
export interface UserGroup {
uId: number;
gId: number;
}
I have two arrays:
finalUserGroupsToUpdate: UserGroup[];
pickListUserAssociatedGroups: Group[];
The array of Group is populated and looks like this in the console:
(3) [{…}, {…}, {…}]
0: {gId: 1, gName: "Manager"}
1: {gId: 2, gName: "Nurse"}
2: {gId: 3, gName: "Audit"}
I also have a uId that is accessible through the active route in Angular (for this example it can just be a local variable):
currentUserID = 1;
What I want to be able to do is push each gId of the array of Group into the array of UserGroup while appending currentUserId as the uId.
The final result should look something like:
(3) [{…}, {…}, {…}]
0: {gId: 1, uId: 1}
1: {gId: 2, uId: 1}
2: {gId: 3, uId: 1}
You can use Array#map.
const arr = [{gId: 1, gName: "Manager"},
{gId: 2, gName: "Nurse"},
{gId: 3, gName: "Audit"}];
let currentUserID = 1;
const res = arr.map(({gId})=>({gId, uId: currentUserID}));
console.log(res);
const finalUserGroupsToUpdate: UserGroup[];
const pickListUserAssociatedGroups: Group[] =[{gId: 1, gName: "Manager"},
{gId: 2, gName: "Nurse"},
{gId: 3, gName: "Audit"}];
const currentUserID = 1;
pickListUserAssociatedGroups.forEach(({gId}) => {
finalUserGroupsToUpdate.push({gId, uId: currentUserID})
});
console.log(finalUserGroupsToUpdate);
Say, you have your groups in arrayOfGroups and you want to assign each group id gId to current user id uId and hold them in array arrayOfUserGroups.
currentUserID = 1;
arrayOfUserGroups = [];
arrayOfGroups.forEach(g => {
arrayOfUserGroups.push({gId: g.gId, uId: currentUserID});
});
I am trying to make a function that counts duplicates, this works but not in the output format I need.
This is my function:
var duplicateCount = {};
countryArray.forEach(e => duplicateCount[e] = duplicateCount[e] ? duplicateCount[e] + 1 :
1);
result5 = Object.keys(duplicateCount).map(e => {return {key:e, count:duplicateCount[e]}});
console.log("result5", result5);
The output I get is:
result5
(3) [{…}, {…}, {…}]
0: {e: "CRM", count: 6}
1: {e: "TSA", count: 8}
2: {e: "PCS", count: 3}
length: 3
__proto__: Array(0)
The output I need is:
result5
(3) [{…}, {…}, {…}]
0: {"CRM", 6}
1: {"TSA", 8}
2: {"PCS", 3}
length: 3
__proto__: Array(0)
Any help is good. Thank!!
Did you mean you want the e property to be the key? (it shows a , instead of :)
const data = [
{e: "CRM", count: 6},
{e: "TSA", count: 8},
{e: "PCS", count: 3}
]
const output1 = data.map(obj => ({[obj.e]:null, [obj.count]:null}))
const output2 = data.map(obj => ({[obj.e]:obj.e, [obj.count]:obj.count}))
const output3 = data.map(obj => ([obj.e, obj.count]))
console.log("output1:",output1, "output2:",output2, "output3:",output3)
I assume you need an array of objects. But {"CRM", 6} is incorrect object syntax. The object should contain key: value pairs.
Use Object.enties and map
countryArray = ["foo", "bar", "foo"];
var duplicateCount = {};
countryArray.forEach((e) => (duplicateCount[e] = (duplicateCount[e] ?? 0) + 1));
result5 = Object.entries(duplicateCount).map(([key, value]) => ({
[key]: value,
}));
console.log("result5", result5);
I have an array that looks like this:
[{location: {…}, distance: 0}
{location: {…}, distance: 0}
{location: {…}, distance: 0.37348441209694133}
{location: {…}, distance: 0}
{location: {…}, distance: 0.4229382782128456}
{location: {…}, distance: 0}
{location: {…}, distance: 0.006098292961396555}
{location: {…}, distance: 0}
{location: {…}, distance: 0.07885846317546494}]
I want to map a new array with the distance values incremented from the previous value. So in the example above the last distance value would be 0.88137944644665 because it was have added all the values by the time it iterated all objects.
In Ramda.js I've tried to add the previous distance value when I map the array but it doesn't work because it's undefined. I've also looked into reduce with no success. Any ideas on how I can accomplish this in Ramda.js?
Much as I love Ramda you don't need it here:
arr.map(({ location, distance }) => ({ location, distance: distance + 1 }));
To break that down:
arr // your array of objects
.map( // call to Array.prototype.map
({ location, distance }, i, arr) => // function params, destructures
({ location, distance: distance + 1 })); // return new object same loc, incremented distance
EDIT
Since I missed the part about aggregation, use reduce instead:
arr.reduce((aggregate, { location, distance }, i) => {
const dist = i ? aggregate[i - 1].distance : 0;
aggregate.push({ location, distance: distance + dist });
return aggregate;
}, []);
Try the following
const reducedData = data.reduce( (prev, val) => {
prev.sum += val.distance
prev.datas.push({
...val,
distance: prev.sum
})
return prev;
}, {sum: 0, datas: []})
The .reduce loops on the data and merges each row into prev. The final output of this script is an object that looks like { sum: number , datas: [...]}, sum in here is the total distance, and the datas will contain the array that you want.
See snapshot:
If you were looking utilise Ramda functions here, R.scan can help. This function is very similar to reduce though instead of returning a single summarised value it will produce a list of every successive result.
const distanceL = R.lensProp('distance')
const addDistance = R.compose(R.add, R.prop('distance'))
const fn = data =>
R.scan(
(acc, next) => R.over(distanceL, addDistance(acc), next),
data[0],
R.tail(data)
)
console.log(fn([
{location: {}, distance: 0},
{location: {}, distance: 0},
{location: {}, distance: 0.37348441209694133},
{location: {}, distance: 0},
{location: {}, distance: 0.4229382782128456},
{location: {}, distance: 0},
{location: {}, distance: 0.006098292961396555},
{location: {}, distance: 0},
{location: {}, distance: 0.07885846317546494}
]))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
Or you could use scan:
const {lift, scan, head, tail} = R
const xs = [
{location: {id: 1}, distance: 0},
{location: {id: 2}, distance: 0},
{location: {id: 3}, distance: 0.37348441209694133},
{location: {id: 4}, distance: 0},
{location: {id: 5}, distance: 0.4229382782128456},
{location: {id: 6}, distance: 0},
{location: {id: 7}, distance: 0.006098292961396555},
{location: {id: 8}, distance: 0},
{location: {id: 9}, distance: 0.07885846317546494}
]
const accumDist = lift(scan((agg, x) => ({...x, distance: x.distance + agg.distance})))(head, tail)
console.log(accumDist(xs))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
This won't work with an empty list. If that's a concern, we could alter it by skipping lift(...)(head, tail) and just using the scan with an initial value, and then taking the tail. But if that's not a concern, this code is clearer.