How can I create the MissingUserIdsArray from MainArray in JavaScript?
var MainArray = [
[
"10148835*1,2,3,",
"1,2,3,4,5,"
],
[
"10148839*4,5,",
"1,2,3,4,5,"
]
];
const MappedArrray = MainArray.map(arr => {
const SplitID = arr[0].split("*");
return {"AppId": SplitID[0], "AppUserIds": SplitID[1].split(","), "MeetingUserIds": arr[1].split(",")};
});
console.log(MappedArrray);
//My above code is working fine. Just need to make MissingUserIdsArray array in the format I mentioned.
const MissingUserIdsArray = MappedArrray.map(arr => arr.MeetingUserIds.filter(x => !arr.AppUserIds.includes(x)));
console.log(MissingUserIdsArray);
//Need to create MissingUserIdsArray in the following format:
/*
MissingUserIdsArray = [
{"AppId": 10148835, "MissingUserIds": "4,5"},
{"AppId": 10148839, "MissingUserIds": "1,2,3"},
]
*/
There wasn't much missing in your code:
The trailing comma in the source data makes me choose match over split
Join the array you had to get the comma separated values
var MainArray = [["10148835*1,2,3,","1,2,3,4,5,"],["10148839*4,5,","1,2,3,4,5,"]];
const MappedArrray = MainArray.map(([a, b]) => {
const [AppId, ...appUserIds] = a.match(/\d+/g);
const MissingUserIds = b.match(/\d+/g).filter(id => !appUserIds.includes(id)).join();
return {AppId, MissingUserIds};
});
console.log(MappedArrray);
Just split up the strings into a processable format and then exclude one set of ids from the other:
const MainArray = [
[
"10148835*1,2,3,",
"1,2,3,4,5,"
],
[
"10148839*4,5,",
"1,2,3,4,5,"
]
];
const result = MainArray
.map( ([s, ids]) => [...s.split('*'), ids.split(',')])
.map(([AppId, excludes, ids]) => (excludes = excludes.split(','), {AppId, MissingUserIds: ids.filter(id => !excludes.includes(id)).join(',') }) )
console.log(result)
Related
I have a problem to filters data inside the array of objects by an array of objects. I already try using filters combine with the includes method but returning an empty array.
let's say I have array an array called listOfPermissions.
listOfPermissions = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
{name:'C',IsChecked:true}
]
Than i want to filter the list with permissionOnRole array
permissionOnRole = [
{name:'C',IsChecked: true}
]
The goals i want to achieve
result = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
]
this is my code
const setUncheckPermissions = () => {
const permissionsOnRole = role.permissions.map(it => ({name: it, isChecked: true}))
const listOfAllPermissions = props.permissions.map((permission) => {return {name: permission['name'], isChecked: true}});
let result = listOfAllPermissions.filter(item => permissionsOnRole.includes(item));
console.log(listOfAllPermissions)
}
please help me to solve this problems
Thank you in advance
Just use filter
const listOfPermissions = [
{name:'A',IsChecked:true},
{name:'B',IsChecked:true},
{name:'C',IsChecked:true}
]
const permissionOnRole = [
{name:'C',IsChecked: true}
]
const result = listOfPermissions.filter(item => !!permissionOnRole.find(i => i.name !== item.name))
console.log(result)
How can I loop through this array:
const counts = [
"900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"20,overflow.com",
"5,com.com",
"2,en.wikipedia.org",
"1,m.wikipedia.org",
"1,mobile.sports",
"1,google.co.uk",
];
taking each value from this array?
const uniqueDomains = [
'google.com',
'com',
'mail.yahoo.com',
'yahoo.com',
'mobile.sports.yahoo.com',
'sports.yahoo.com',
'stackoverflow.com',
'overflow.com',
'com.com',
'en.wikipedia.org',
'wikipedia.org',
'org',
'm.wikipedia.org',
'mobile.sports',
'sports',
'google.co.uk',
'co.uk',
'uk'
]
I need to find out if string from counts array includes string from uniqueDomains array.
Then push it to the empty object as a key value pairs, where value
is going to be the number in the beginning of the each string from counts array.
I tried this code but it give me wrong result in my object's values(since I am looping twice)
I need kind of avoid looping twice, but I am not sure how.
Example com is mentioned 8 time in counts array, which means result should be this {com: 1345}
Here is my code:
const finalObject = {}
uniqueDomains.forEach((dom) => {
counts.forEach((cnt) => {
if (cnt.includes(dom)) {
const num = parseInt(cnt);
sumArr.push(num);
const res = sumArr.reduce((acc, cur) => {
return acc + cur;
});
finalObject[dom] = res;
}
});
});
Theres not really any avoiding looping twice (at least), but you can certainly make your code a bit easieer by first turning the count array into an array of val & domain separately.
const countIdx = counts.map(x => {
const [val,domain] = x.split(",");
return {val:parseInt(val,10), domain}
});
Then its just a case of looping the uniqueDomain array and finding all the domaion which match and summing up the val
const result = uniqueDomains.reduce( (res, d) => {
const count = countIdx.filter(x => x.domain.includes(d)).reduce( (acc,x) => acc + x.val,0);
return {...res, [d]:count}
},{});
Live example follows:
const counts = [
"900,google.com",
"60,mail.yahoo.com",
"10,mobile.sports.yahoo.com",
"40,sports.yahoo.com",
"300,yahoo.com",
"10,stackoverflow.com",
"20,overflow.com",
"5,com.com",
"2,en.wikipedia.org",
"1,m.wikipedia.org",
"1,mobile.sports",
"1,google.co.uk",
];
const uniqueDomains = [
'google.com',
'com',
'mail.yahoo.com',
'yahoo.com',
'mobile.sports.yahoo.com',
'sports.yahoo.com',
'stackoverflow.com',
'overflow.com',
'com.com',
'en.wikipedia.org',
'wikipedia.org',
'org',
'm.wikipedia.org',
'mobile.sports',
'sports',
'google.co.uk',
'co.uk',
'uk'
]
const countIdx = counts.map(x => {
const [val,domain] = x.split(",");
return {val:parseInt(val,10), domain}
});
const result = uniqueDomains.reduce( (res, d) => {
const count = countIdx.filter(x => x.domain.includes(d)).reduce( (acc,x) => acc + x.val,0);
return {...res, [d]:count}
},{});
console.log(result);
Maybe try something like:
let finalObject = {}
uniqueDomains.forEach((dom) => {
finalObject[dom] = 0;
counts.forEach((cnt) => {
if (cnt.includes(dom)) {
finalObject[dom] += parseInt(cnt);
}
});
});
i'm new here, i have problem that i can not solve.
I have 2 different arrays:
The first array - contains ratings of users with their ID name
[
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
]
The second set - contains the ratings, which I want to return to each user.
If there is a rating that is not in the second set, I will not return it
In the second set, values do not matter, only keys
[
"_assembler",
"_css",
"_python",
"_php"
]
I want to return to the first set, the handle, and all the rankings that exist in the second set.
[
{"handle":"frontend1", "_python":"3" },
{"handle":"frontend3", "_php":"4", "_python":"5" },
{"handle":"frontend4"}
]
this is what i try to do.
keys = [
"_assembler",
"_css",
"_python",
"_php"
]
source = [
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
];
result = [];
tmp = {};
source.forEach((item) => {
Object.keys(item).map(({key,value}) =>
{
if(key == "handle")
{
tmp[key]=value;
}
if(keys.includes(key))
{
tmp[key]=value;
}
})
result.push(...tmp);
tmp = {};
});
You can do this with a map utilizing a couple of other array methods such as filter, and Object methods.
const keys = [
"_assembler",
"_css",
"_python",
"_php"
]
const source = [
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
];
const result = source.map( s => ({
handle: s.handle,
...Object.fromEntries(Object.entries(s).filter(x => x[0] != "handle" && keys.includes(x[0])))
}));
console.log(result);
I have got array of nested array of objects .
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
I want to convert array to this format of objects and I want to get this output
let permission ={
group:["1"],
topGroup:["2"]
}
How can I do this ?
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
const converted = data.reduce((a,b) => {
const onlyKey = Object.keys(b)[0];
a[onlyKey] = b[onlyKey].map(i => i.label);
return a;
}, {})
console.log(converted)
const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
let permission = {};
data.forEach(val =>{
for(prop in val){
permission[prop] = [val[prop][0]["label"]]
}
})
console.log(permission)
Give this a upvote if this is what you want.
Assuming the data is going to have labels as in that format forever, you could use something like that
const data = [{"group":[{"label":"1"}]},{"topGroup":[{"label":"12"}]}];
// The dict variable under here is the second parameter of reduce that I passed it `{}`.
// The ind variable is the data at the index of the array.
var newData = data.reduce(function(dict, ind){
// You basically get the keys and the values and put them in place
// and return the last state to the reduce function.
dict[Object.keys(ind)] = Object.values(ind)[0][0]["label"];
return dict;
}, {})
console.log(newData)
Use destructuring and Object.fromEntries.
const data = [{ group: [{ label: "1" }] }, { topGroup: [{ label: "2" }] }];
const permission = Object.fromEntries(
data.map(item => {
const [[key, [obj]]] = Object.entries(item);
return [key, Object.values(obj)];
})
);
console.log(permission);
I got problem, I've array of string as
[
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
I need to convert it to Object
[
{"Time" : "25/10/2019 14:49:47.41", "Server", "Daniel.Europe..", .. },
{}
]
likewise.
JSON.parse won't work on non-serialized string.
Using Object.fromEntries()
var data = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
var result = data.map(v =>
Object.fromEntries(v.split(',').map(v => v.split(/:(.*)/)))
)
console.log(result)
Something like this should work:
input.map(v => v.split(',').map(v => {
const [key, ...value] = v.split(':');
const obj = {};
obj[key] = value.join(':');
return obj;
}))
You can get it using map and reduce:
const arr = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
]
const newArr = arr.map(item => {
return item.split(",").reduce((acc, curr) => {
const label = curr.split(":")[0];
const value = curr.substring(label.length+1)
acc[curr.split(":")[0]] = value
return acc;
},{})
})
console.log(newArr)
You have to split your strings by commas and colons. Only problem is that your time string has a bunch of colons in it. Here is a start.
var a = [
"Time:25/10/2019 14:49:47.41,Server:Daniel.Europe.A…itical,Area:Europe,Site:,Station:Aberdeen,Stream:",
"Time:25/10/2019 14:49:48.16,Server:Daniel.Europe.U…,Area:Europe,Site:United Kingdom,Station:,Stream:"
];
b = a.map(function(line) {
var obj = {};
line.split(",").forEach(function(item) {
kv = item.split(/:(.+)/,2);
obj[kv[0]]=kv[1];
});
return obj;
});
console.log(b);