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);
Related
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 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
I have an array of array of objects similar to this:
arr = [{
val: 1,
ts: 123
}, {
val: 2,
ts: 125
}, {
val: 3,
ts: 120
}, {
val: 4,
ts: 113
}, {
val: 5,
ts: 117
}, {
val1: 6,
ts: 143
}, {
val1: 7,
ts: 193
}, {
val1: 8,
ts: 187
}, {
val1: 9,
ts: 115
}, {
val1: 10,
ts: 116
}]
The length of the array is always an even number. Now basically I'd like to split them in 2 halves
split1 = [{ val:1}, {val :2}, ......{val:5}]
split2 = [{val1:6},{val1:7},.......{val1:10}]
Now I have to map over these arrays and combine their fields(first item of array1 with first item of array2 and so on) into one single object and add an extra id to it such that result will look like
final = [{val:1, val1:6 , id:1} , {val:2, val1:7,id:3} , {val:3, val1:8,id:3},{val:4, val1:9,id:4},{val: 5, val1:10, id:5}]
This should hold for all arrays of even length and I want to make it a dynamic one. Keys will never be repeated inside source array
What I have tried is:
var res= a.splice(0, arr.length/2);
var c = a.map((val, ind) => { {val, res[ind]} })
Can someone guide here?
You can try this solution
const arr = [{ val: 1},{val: 2},{val: 3}, {val: 4} , {val:5},{ val1: 6},{val1: 7},{val1: 8}, {val1: 9} , {val1:10}]
const split = arr => [arr.slice(0, arr.length/2), arr.slice(arr.length/2, arr.length)]
const splitedArr = split(arr);
const merge = arr => {
const merged = []
for(let i = 0; i < arr[0].length; i++){
let newObj = {...arr[0][i], ...arr[1][i], id:(i+1)}
merged.push(newObj);
}
return merged;
}
const mergedArr = merge(splitedArr);
console.log(mergedArr);
You're quite close, some minor fixes
wrap map function implicit return with () instead of {}
for adding computed value you need to assign key name explicitly
need to destructure val or need to access val.val
const arr = [{ val: 1}, {val: 2}, {val: 3}, {val: 4}, {val: 5}, {val1: 6}, {val1: 7}, {val1: 8}, {val1: 9}, {val1: 10}];
const firstHalf = arr.slice(0, arr.length / 2);
const secondHalf = arr.slice(arr.length / 2);
const final = secondHalf.map((val, ind) => ({
...val,
...firstHalf[ind],
id: ind,
}))
console.log(final);
I have tried
var res= a.splice(0, arr.length/2);
var c = a.map((val, ind) => { {val, res[ind]} })
You're quite close. To make the map callback syntactically valid and create the desired object, it should be
var res = a.splice(0, arr.length/2);
var c = a.map((val, ind) => {
return {val: val.val, val1: res[ind].val1, id: ind+1};
})
or
var c = a.map((val, ind) => {
return Object.assign({id: ind+1}, val, res[ind]);
})
I am trying to rename the json but it generates the following error
var kvArray = [
{0: 'cat', 1: 1, 2: "sunt"},
{0: 'dog', 1: 2, 2: "qui"},
{0: 'mouse',1: 3, 2: "repell"}
];
var newArray = kvArray.map((elm) => {
var mappedElm = { animal: elm.0, age: elm.1, name: elm.2};
return mappedElm;
});
console.log(newArray)
The object represented in the JSON is an numerically indexed array, not an object.
You probably need to use the [] index contstruct as follows
var kvArray = [
{0: 'cat', 1: 1, 2: "sunt"},
{0: 'dog', 1: 2, 2: "qui"},
{0: 'mouse',1: 3, 2: "repell"}
];
var newArray = kvArray.map((elm) => {
var mappedElm = { animal: elm[0], age: elm[1], name: elm[2]};
return mappedElm;
});
console.log(newArray)