get the indexOf of a cascaded array of objects - javascript

I'm trying and puzzling for a couple of hours now and I can't get my head around it.
I have the following data structure in Redux:
entities: {
users: {
dentists: [
{
id: 1,
first_name: 'Tessa',
last_name: 'Iiannone',
phone: '+234 325 319 4277',
email: 'tiiannone0#dentistcompanybvt.com'
},
{
id: 2,
first_name: 'Kennett',
last_name: 'Pedreschi',
phone: '+48 204 144 9885',
email: 'kpedreschi1#dentistcompanybvt.com'
},
{
id: 3,
first_name: 'Lorine',
last_name: 'Tolle',
phone: '+670 691 959 9810',
email: 'ltolle2#dentistcompanybvt.com'
},
{
id: 4,
first_name: 'Nessi',
last_name: 'Pikhno',
phone: '+995 756 907 2258',
email: 'npikhno3#dentistcompanybvt.com'
}
],
assistants: [
{
id: 1,
first_name: 'Nickolas',
last_name: 'Seamans',
phone: '+62 949 597 4013',
email: 'nseamans0#dentistcompanybvt.com'
},
{
id: 2,
first_name: 'Peri',
last_name: 'Helversen',
phone: '+51 886 232 9275',
email: 'phelversen1#dentistcompanybvt.com'
}
],
clients: [
{
id: 1,
first_name: 'Mona',
last_name: 'Shakelade',
phone: '+63 475 243 2059',
email: 'mshakelade0#sourceforge.net',
date_of_birth: '26/01/1987',
status: null
},
{
id: 2,
first_name: 'Dario',
last_name: 'Aizikovitz',
phone: '+33 454 959 7355',
email: 'daizikovitz1#buzzfeed.com',
date_of_birth: '16/08/1999',
status: null
},
{
id: 3,
first_name: 'Caren',
last_name: 'Chidgey',
phone: '+358 905 256 6974',
email: 'cchidgey2#imgur.com',
date_of_birth: '08/03/1983',
status: null
},
{
id: 4,
first_name: 'Timmi',
last_name: 'Weond',
phone: '+225 796 207 5915',
email: 'tweond3#dion.ne.jp',
date_of_birth: '25/08/1972',
status: null
},
{
id: 5,
first_name: 'Greer',
last_name: 'Cornelius',
phone: '+46 793 784 2482',
email: 'gcornelius4#ask.com',
date_of_birth: '29/03/1968',
status: null
},
{
id: 6,
first_name: 'Catlee',
last_name: 'Elmar',
phone: '+33 826 857 9849',
email: 'celmar5#economist.com',
date_of_birth: '25/11/1976',
status: null
},
{
id: 7,
first_name: 'Ilsa',
last_name: 'Tynnan',
phone: '+591 283 830 4992',
email: 'itynnan6#illinois.edu',
date_of_birth: '19/02/1992',
status: null
},
{
id: 8,
first_name: 'Delia',
last_name: 'Blueman',
phone: '+55 392 389 4499',
email: 'dblueman7#printfriendly.com',
date_of_birth: '09/11/1975',
status: null
},
{
id: 9,
first_name: 'Lorilyn',
last_name: 'Semens',
phone: '+7 271 804 0493',
email: 'lsemens8#zimbio.com',
date_of_birth: '17/03/2001',
status: null
},
{
id: 10,
first_name: 'Lorilee',
last_name: 'Slemmonds',
phone: '+63 858 699 0861',
email: 'lslemmonds9#umich.edu',
date_of_birth: '20/07/1991',
status: null
}
]
},
appts: {
id: 1,
date: '01012022',
hour: 8,
client_id: 1,
dentist_id: 1,
assistant_id: 1
},
ui: {
ids: [
1
],
entities: {
'1': {
id: 1,
usertype: 'client'
}
}
}
}
}
I combined the 3 lists in my slice with:
const users = { dentists: dentists, assistants: assistants, clients: clients };
So now i expect that when i say:
const index = users.clients.indexOf((user) => user.id === action.payload.id)
...wil give me the index of the matching item with action.payload.id, but I'll keep on getting -1 when I do a console.log(index) what means that there is no match.
Can anyone help me out here?
What am I doing wrong?

indexOf requires an element. You can use find to get the element first and get the index next:
console.log(users.clients.indexOf(users.clients.find(client => client.id === action.payload.id)));
findIndex requires a callback, which is the requirement in your case, as you look for an object that you don't know, but can find by id:
console.log(users.clients.findIndex((client) => client.id == action.payload.id));

Related

Map array and group by roles in the array object

I have an object array, And in that I have roles as a key, And values init.
Now what I want is I want to group them as per the roles.
This is my data input
{
users: [
{
firstName: 'Will',
lastName: 'Jacob',
email: 'sample#sample.com',
_id: '5e324187b5fdf167a91dfdbb',
roles: [ 'ward', 'hospital', 'hr' ],
},
{
firstName: 'Theatre',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf2f0c631a8788be59fc4',
roles: [ 'ward' ],
},
{
firstName: 'Cinema',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema2',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['ward', 'hr' ],
},
{
firstName: 'Cinema3',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema4',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: [ 'ward', 'hospital', 'hr' ],
}
]}
AND I want to group it by roles in them and want output something like below
{
ward: [{
firstName: 'Will',
lastName: 'Jacob',
email: 'sample#sample.com',
_id: '5e324187b5fdf167a91dfdbb',
roles: [ 'ward', 'hospital', 'hr' ],
},
{
firstName: 'Theatre',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf2f0c631a8788be59fc4',
roles: [ 'ward' ],
},
{
firstName: 'Cinema2',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['ward', 'hr' ],
},
{
firstName: 'Cinema3',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: [ 'ward', 'hospital', 'hr' ],
}],
hospital: [
{
firstName: 'Will',
lastName: 'Jacob',
email: 'sample#sample.com',
_id: '5e324187b5fdf167a91dfdbb',
roles: [ 'ward', 'hospital', 'hr' ],
},
{
firstName: 'Cinema',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema3',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema4',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: [ 'ward', 'hospital', 'hr' ],
}],
hr: [{
firstName: 'Will',
lastName: 'Jacob',
email: 'sample#sample.com',
_id: '5e324187b5fdf167a91dfdbb',
roles: [ 'ward', 'hospital', 'hr' ],
},
{
firstName: 'Cinema',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema2',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['ward', 'hr' ],
},
{
firstName: 'Cinema3',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: ['hospital', 'hr' ],
},
{
firstName: 'Cinema4',
lastName: 'Manager',
email: 'sample#sample.com',
_id: '5e3cf62cc631a8788be59fc5',
roles: [ 'ward', 'hospital', 'hr' ],
}
]
}
How can I achieve this? I am looking for a function to process this and return the output as requried.
Please find the Array.reduce implementation.
Logic
Loop through each object in array
Loop through the roles array in each object.
Check if the accumulator have a node with that role, if yes push to that node in accumulator, or else create a node with that name and current object as an element of that node
Working Example
const data = {"users":[{"firstName":"Will","lastName":"Jacob","email":"sample#sample.com","_id":"5e324187b5fdf167a91dfdbb","roles":["ward","hospital","hr"]},{"firstName":"Theatre","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf2f0c631a8788be59fc4","roles":["ward"]},{"firstName":"Cinema","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf62cc631a8788be59fc5","roles":["hospital","hr"]},{"firstName":"Cinema2","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf62cc631a8788be59fc5","roles":["ward","hr"]},{"firstName":"Cinema3","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf62cc631a8788be59fc5","roles":["hospital","hr"]},{"firstName":"Cinema4","lastName":"Manager","email":"sample#sample.com","_id":"5e3cf62cc631a8788be59fc5","roles":["ward","hospital","hr"]}]};
const output = data.users.reduce((acc, curr) => {
curr.roles.forEach((role) => {
acc[role] ? acc[role].push(curr) : acc[role] = [curr];
})
return acc;
}, {});
console.log(output);
You can use array#reduce to group your data based on roles. You can iterate through each object and create separate array for each role type. This solution only require single traversal of your input array.
const input = { users: [ { firstName: 'Will', lastName: 'Jacob', email: 'sample#sample.com', _id: '5e324187b5fdf167a91dfdbb', roles: [ 'ward', 'hospital', 'hr' ], }, { firstName: 'Theatre', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf2f0c631a8788be59fc4', roles: [ 'ward' ], }, { firstName: 'Cinema', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf62cc631a8788be59fc5', roles: ['hospital', 'hr' ], }, { firstName: 'Cinema2', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf62cc631a8788be59fc5', roles: ['ward', 'hr' ], }, { firstName: 'Cinema3', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf62cc631a8788be59fc5', roles: ['hospital', 'hr' ], }, { firstName: 'Cinema4', lastName: 'Manager', email: 'sample#sample.com', _id: '5e3cf62cc631a8788be59fc5', roles: [ 'ward', 'hospital', 'hr' ], }]},
result = input.users.reduce((r, o) => {
o.roles.forEach(role => {
r[role] ??= [];
r[role].push(JSON.parse(JSON.stringify(o)));
});
return r;
},{});
console.log(result);
You can just go over each input element and then over each role in the input element and add the element to the corresponding array in a by-role object (creating the array as needed):
const byRole = {}
for (const obj of input.users) {
for (const role of obj.roles) {
if (!byRole[role]) byRole[role] = []
byRole[role].push(obj)
}
}
console.log(byRole)
There would be also a less imperative, more functional approach, if you prefer that:
const byRole = Object.fromEntries(
[...new Set(input.users.map(obj => obj.roles).flat())]
.map(role => [role, inputArray.filter(obj => obj.roles.includes(role))])
)
console.log(byRole)
Since you seem to be working with MongoDB records, another possibility would be to group it already in your database query, offloading that work to the database server:
const queryResult = await db.users.aggregate([
// Optionally add a $match step here to filter: { $match: { ... } }
{ $addFields: { role: '$roles' } },
{ $unwind: '$role' },
{ $group: { _id: '$role', records: { $push: '$$ROOT' } } }
])
const byRole = Object.fromEntries(
queryResult.map(({ _id, records }) => [_id, records])
)
(This will leave an extra field role in each record though, but I guess you won't mind.)

how to refactor array from array to single array using javascript

const arr = [
[
{
_id: "6136096f4255d84bcb4a7144",
user_id: "5fbfa729fc46a415ce5503a6",
picture: [Array],
timestamp: 1630931311227,
},
user: {
_id: "5fbfa729fc46a415ce5503a6",
first_name: "ABC",
last_name: "AAA",
picture: [Object]
}
],
[
{
_id: "613609414255d84bcb4a7122",
user_id: "5fbf6f91aff7f3320a906547",
picture: [Array],
device_platform: 'ios',
timestamp: 1630931265409
},
user: {
_id: "5fbf6f91aff7f3320a906547",
first_name: 'EEE',
last_name: 'TTT',
picture: [Object]
}
],
[
{
_id: "613709f49223350dfdaec618",
user_id: "5fbfa748fc46a415ce5503a8",
picture: [Array],
timestamp: 1630996980379
},
{
_id: "613609184255d84bcb4a710a",
user_id: "5fbfa748fc46a415ce5503a8",
picture: [Array],
timestamp: 1630931224383,
},
user: {
_id: "5fbfa748fc46a415ce5503a8",
first_name: 'GRT',
last_name: 'GGG',
picture: [Object]
}
]
]
I merged push into the object one were like res = [{_id: ..., user_id: ...},{_id: ..., user_id: ...}] and other one was like user = {_id: 5fbfa748fc46a415ce5503a8, first_name: 'AAA',last_name : 'DD'}
res.user = user;
array.push(res)
I merged two object it bring up this but it does not seems to be correct response.
when I used var merged = [].concat.apply([], arr); it does not work
how to fix with correct format.
Working code! just remove the user key from the array, and one note ) use const/let instead of var
const arr = [
[
{
_id: "6136096f4255d84bcb4a7144",
user_id: "5fbfa729fc46a415ce5503a6",
picture: [Array],
timestamp: 1630931311227,
},
{
_id: "5fbfa729fc46a415ce5503a6",
first_name: "ABC",
last_name: "AAA",
picture: [Object]
}
],
[
{
_id: "613609414255d84bcb4a7122",
user_id: "5fbf6f91aff7f3320a906547",
picture: [Array],
device_platform: 'ios',
timestamp: 1630931265409
},
{
_id: "5fbf6f91aff7f3320a906547",
first_name: 'EEE',
last_name: 'TTT',
picture: [Object]
}
],
[
{
_id: "613709f49223350dfdaec618",
user_id: "5fbfa748fc46a415ce5503a8",
picture: [Array],
timestamp: 1630996980379
},
{
_id: "613609184255d84bcb4a710a",
user_id: "5fbfa748fc46a415ce5503a8",
picture: [Array],
timestamp: 1630931224383,
},
{
_id: "5fbfa748fc46a415ce5503a8",
first_name: 'GRT',
last_name: 'GGG',
picture: [Object]
}
]
]
const merged = [].concat.apply([], arr);
console.log(merged);

Datatables Checkbox Multi Select

I am using datatables v1.10 and i'm offering the user a number of select boxes in order to filter results. I want to filter the contents a specific column depending on their selection.
I'm building an inventory of volunteers that is searchable and discoverable by the local community.
They need to be able to filter on single and multiple values. So if they select Collection the table should display only results containing Collection. If they select Collection and Cleaning the table should display only results containing Collection and Cleaning (not Delivery). etc.
Currently my table only filters based on a single selection.
Here's a fiddle. Code also below;
Suggestions would be appreciated.
$(document).ready(function () {
var data = [
{
id: 1,
full_name: "Andrea Ragg",
email: "aragg0#netlog.com",
telephone: "584-78-0505",
location: "Derry",
service: "Collection",
availability: 0
},
{
id: 2,
full_name: "Thornton Keeri",
email: "tkeeri1#imageshack.us",
telephone: "503-58-8194",
location: "Cork",
service: "Collection, Cleaning, Delivery",
availability: 0
},
{
id: 3,
full_name: "Reuven Beddis",
email: "rbeddis2#china.com.cn",
telephone: "412-16-2320",
location: "Galway",
service: "Delivery, Collection",
availability: 0
},
{
id: 4,
full_name: "Phil Bardwall",
email: "pbardwall3#phpbb.com",
telephone: "864-82-5385",
location: "Cork",
service: "Collection, Cleaning, Delivery",
availability: 0
},
{
id: 5,
full_name: "Torey Jefford",
email: "tjefford4#seesaa.net",
telephone: "879-42-9577",
location: "Cork",
service: "Cleaning, Delivery",
availability: 1
},
{
id: 6,
full_name: "Chandler Robe",
email: "crobe5#biblegateway.com",
telephone: "299-07-6714",
location: "Derry",
service: "Collection",
availability: 0
},
{
id: 7,
full_name: "Rollie Boorn",
email: "rboorn6#g.co",
telephone: "358-94-3758",
location: "Derry",
service: "Delivery",
availability: 0
},
{
id: 8,
full_name: "Andie Daulton",
email: "adaulton7#nydailynews.com",
telephone: "776-32-4779",
location: "Derry",
service: "Collection, Cleaning, Delivery",
availability: 1
},
{
id: 9,
full_name: "Andonis Knagges",
email: "aknagges8#live.com",
telephone: "879-70-4074",
location: "Galway",
service: "Cleaning",
availability: 1
},
{
id: 10,
full_name: "Marney Moreinis",
email: "mmoreinis9#jalbum.net",
telephone: "324-76-8540",
location: "Dublin",
service: "Cleaning, Collection",
availability: 0
},
{
id: 11,
full_name: "Jean Drayson",
email: "jdraysona#biglobe.ne.jp",
telephone: "741-85-8028",
location: "Dublin",
service: "Cleaning, Collection, Delivery",
availability: 1
},
{
id: 12,
full_name: "Rhea Troubridge",
email: "rtroubridgeb#theguardian.com",
telephone: "342-47-7173",
location: "Dublin",
service: "Cleaning, Delivery",
availability: 1
},
{
id: 13,
full_name: "Cord Habergham",
email: "chaberghamc#columbia.edu",
telephone: "400-95-9506",
location: "Cork",
service: "Cleaning, Delivery, Collection",
availability: 0
},
{
id: 14,
full_name: "Otha Hiers",
email: "ohiersd#facebook.com",
telephone: "697-07-9372",
location: "Dublin",
service: "Cleaning, Delivery",
availability: 0
},
{
id: 15,
full_name: "Edna Barg",
email: "ebarge#wix.com",
telephone: "210-66-2867",
location: "Dublin",
service: "Cleaning, Collection, Delivery",
availability: 1
},
{
id: 16,
full_name: "Rozalin Wilmut",
email: "rwilmutf#freewebs.com",
telephone: "732-74-0848",
location: "Galway",
service: "Cleaning",
availability: 0
},
{
id: 17,
full_name: "Glen Darben",
email: "gdarbeng#google.com.au",
telephone: "570-01-5383",
location: "Galway",
service: "Cleaning, Collection, Delivery",
availability: 0
},
{
id: 18,
full_name: "Wally Longstaff",
email: "wlongstaffh#reference.com",
telephone: "278-18-3965",
location: "Belfast",
service: "Delivery",
availability: 1
},
{
id: 19,
full_name: "Moise Murrhardt",
email: "mmurrhardti#t.co",
telephone: "165-08-4136",
location: "Dublin",
service: "Delivery, Cleaning, Collection",
availability: 1
},
{
id: 20,
full_name: "Gloria Tedder",
email: "gtedderj#ucoz.ru",
telephone: "809-19-8763",
location: "Dublin",
service: "Delivery, Collection, Cleaning",
availability: 0
},
{
id: 21,
full_name: "Marthena Pavel",
email: "mpavelk#state.tx.us",
telephone: "180-16-5508",
location: "Derry",
service: "Cleaning",
availability: 1
},
{
id: 22,
full_name: "Livvy Tesoe",
email: "ltesoel#timesonline.co.uk",
telephone: "748-54-7269",
location: "Derry",
service: "Collection, Cleaning",
availability: 1
},
{
id: 23,
full_name: "Angelle Tondeur",
email: "atondeurm#ebay.com",
telephone: "761-27-3445",
location: "Galway",
service: "Cleaning, Collection",
availability: 1
},
{
id: 24,
full_name: "Marsiella Van Schafflaer",
email: "mvann#europa.eu",
telephone: "330-85-4309",
location: "Derry",
service: "Delivery, Cleaning",
availability: 1
},
{
id: 25,
full_name: "Norene Pettegree",
email: "npettegreeo#marketwatch.com",
telephone: "324-47-1541",
location: "Galway",
service: "Delivery",
availability: 0
},
{
id: 26,
full_name: "Gay Newcome",
email: "gnewcomep#free.fr",
telephone: "633-37-5490",
location: "Derry",
service: "Delivery, Cleaning",
availability: 1
},
{
id: 27,
full_name: "Karrah Peltzer",
email: "kpeltzerq#alibaba.com",
telephone: "785-01-1150",
location: "Belfast",
service: "Collection",
availability: 1
},
{
id: 28,
full_name: "Corrinne Gilli",
email: "cgillir#4shared.com",
telephone: "390-05-7538",
location: "Belfast",
service: "Collection",
availability: 1
},
{
id: 29,
full_name: "Jaymee Townrow",
email: "jtownrows#walmart.com",
telephone: "561-19-2949",
location: "Belfast",
service: "Delivery",
availability: 0
},
{
id: 30,
full_name: "Sarita Siggs",
email: "ssiggst#berkeley.edu",
telephone: "272-85-9311",
location: "Belfast",
service: "Delivery, Cleaning, Collection",
availability: 1
},
{
id: 31,
full_name: "Crissie Connerry",
email: "cconnerryu#bbb.org",
telephone: "429-41-7759",
location: "Belfast",
service: "Delivery",
availability: 1
},
{
id: 32,
full_name: "Pincus Olyfant",
email: "polyfantv#flickr.com",
telephone: "554-04-4124",
location: "Dublin",
service: "Cleaning",
availability: 1
},
{
id: 33,
full_name: "Joela Spearett",
email: "jspearettw#slashdot.org",
telephone: "249-42-3733",
location: "Cork",
service: "Collection, Cleaning",
availability: 0
},
{
id: 34,
full_name: "Teodora Floyd",
email: "tfloydx#pcworld.com",
telephone: "867-72-6127",
location: "Dublin",
service: "Cleaning, Collection",
availability: 0
},
{
id: 35,
full_name: "Sherrie Minall",
email: "sminally#google.co.uk",
telephone: "698-47-8076",
location: "Cork",
service: "Collection",
availability: 0
},
{
id: 36,
full_name: "Ikey Sowerby",
email: "isowerbyz#washingtonpost.com",
telephone: "428-82-5186",
location: "Dublin",
service: "Cleaning",
availability: 1
},
{
id: 37,
full_name: "Dasie Skelhorn",
email: "dskelhorn10#trellian.com",
telephone: "804-03-0371",
location: "Derry",
service: "Delivery, Collection, Cleaning",
availability: 0
},
{
id: 38,
full_name: "Wilburt Pickard",
email: "wpickard11#edublogs.org",
telephone: "130-53-6389",
location: "Cork",
service: "Delivery",
availability: 1
},
{
id: 39,
full_name: "Marven Poutress",
email: "mpoutress12#joomla.org",
telephone: "630-06-8139",
location: "Galway",
service: "Collection, Cleaning, Delivery",
availability: 0
},
{
id: 40,
full_name: "Sheff Ruck",
email: "sruck13#vinaora.com",
telephone: "132-51-1884",
location: "Derry",
service: "Collection",
availability: 1
},
{
id: 41,
full_name: "Hyacinth Botcherby",
email: "hbotcherby14#toplist.cz",
telephone: "861-11-1370",
location: "Belfast",
service: "Collection, Cleaning",
availability: 0
},
{
id: 42,
full_name: "Renato Jouhan",
email: "rjouhan15#yahoo.com",
telephone: "616-39-1823",
location: "Belfast",
service: "Delivery, Collection, Cleaning",
availability: 1
},
{
id: 43,
full_name: "Fayth Alwin",
email: "falwin16#unc.edu",
telephone: "887-35-7269",
location: "Dublin",
service: "Delivery, Collection",
availability: 0
},
{
id: 44,
full_name: "Hadrian Gatlin",
email: "hgatlin17#biblegateway.com",
telephone: "615-44-7488",
location: "Dublin",
service: "Delivery, Collection, Cleaning",
availability: 0
},
{
id: 45,
full_name: "Rois Fife",
email: "rfife18#deviantart.com",
telephone: "655-09-6453",
location: "Galway",
service: "Delivery",
availability: 1
},
{
id: 46,
full_name: "Pavlov Pactat",
email: "ppactat19#nature.com",
telephone: "261-25-9415",
location: "Cork",
service: "Delivery",
availability: 0
},
{
id: 47,
full_name: "Brocky Burnell",
email: "bburnell1a#blinklist.com",
telephone: "644-47-6112",
location: "Belfast",
service: "Delivery, Cleaning, Collection",
availability: 0
},
{
id: 48,
full_name: "Naoma Brimson",
email: "nbrimson1b#elpais.com",
telephone: "751-85-9640",
location: "Belfast",
service: "Delivery",
availability: 0
},
{
id: 49,
full_name: "Valma Reddoch",
email: "vreddoch1c#buzzfeed.com",
telephone: "110-89-6953",
location: "Derry",
service: "Collection, Delivery, Cleaning",
availability: 1
},
{
id: 50,
full_name: "Ebony Kilsby",
email: "ekilsby1d#engadget.com",
telephone: "604-37-4930",
location: "Belfast",
service: "Delivery",
availability: 1
}
];
dataTable = $("#example").DataTable({
data: data,
responsive: true,
//dom: '<"top"f>rt<"bottom"p><"clear">',
language: {
searchPlaceholder: "Search records"
},
columns: [
{ data: "id" },
{ data: "full_name" },
{ data: "email" },
{ data: "telephone" },
{ data: "location" },
{ data: "service" },
{
data: "availability",
render: function (data, type, row, meta) {
if (data === 0) {
return '<span class="badge badge-secondary">busy</span>'
;
}
if (data === 1) {
return '<span class="badge badge-success">available</span>'
;
}
}
}
],
columnDefs: [
{
targets: [0, 2, 3, 5],
orderable: false
}
]
});
$('.filter-checkbox').on('change', function(e){
var searchTerms = []
$.each($('.filter-checkbox'), function(i,elem){
if($(elem).prop('checked')){
searchTerms.push("^" + $(this).val() + "$")
}
})
dataTable.column(5).search(searchTerms.join('|'), true, false, true).draw();
});
});
.filter-checkbox{
margin-left: 30px
}
.filter-checkbox:first-child{
margin-left:0
}
<link href="https://cdn.datatables.net/responsive/2.2.3/css/responsive.dataTables.min.css" rel="stylesheet"/>
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.2.3/js/dataTables.responsive.min.js"></script>
<div class="container">
<div class="row">
<div class="col py-3 text-center">
<h2>Community Connect</h2>
<p class="lead text-muted">Table will filter as you type.</p>
</div>
</div>
<div class="row">
<div class="col-8">
<div class="filter-wrapper">
<input type="checkbox" class="filter-checkbox" value="collection"/> Collection
<input type="checkbox" class="filter-checkbox" value="delivery"/> Delivery
<input type="checkbox" class="filter-checkbox" value="cleaning"/> Cleaning
</div>
</div>
</div>
<div class="row">
<div class="col py-3">
<table id="example" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Telephone</th>
<th>Location</th>
<th>Service Offered</th>
<th>Availability</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
Add hidden columns for each checkbox value with something as simple as a true/false in that column. Then you can have each checkbox filter against their column and set the value to filter by based on whether the checkbox is checked. While you adding more columns, it makes the filtering simple.
A more complex solution is to use a multi-select on a single column, likely hidden, and dynamically build a regex to filter the column. I use this for a dynamic multi-select option list, but since your options seem static, the hidden columns seems like an easier approach.

I'm getting empty array what is wrong?

I want the universities that have the string "Uni" included in their name. then, Create a new array called uni that contains them all. I've use the HOF method still didn't work.
var graduates = [{ id: 4, first_name: "Modestine", university: "International Medical & Technological University", email: "mdolder3#symantec.com" },
{ id: 5, first_name: "Chick", university: "Sultan Salahuddin Abdul Aziz Shah Polytechnic", email: "camorts4#google.com.au" },
{ id: 6, first_name: "Jakob", university: "Fachhochschule Rosenheim, Hochschule für Technik und Wirtschaft", email: "jharken5#spiegel.de" },
{ id: 7, first_name: "Robbi", university: "Salem University", email: "rbrister6#redcross.org" },
{ id: 8, first_name: "Colline", university: "Coastal Carolina University", email: "cbrosh7#alibaba.com" },
{ id: 9, first_name: "Michail", university: "Universidad Católica de Ávila", email: "mrome8#shinystat.com" },
{ id: 10, first_name: "Hube", university: "Universitat Rovira I Virgili Tarragona", email: "hlethbrig9#foxnews.com" }]
const unisWithUni = [];
console.log(unisWithUni);
for (let i = 0; i < graduates.length; i++) {
if (graduates[i].university === "Uni") {
unisWithUni.push(graduates[i]);
}
}
You should change graduates[i].university === "Uni" to graduates[i].university.includes("Uni") this way any string that contains 'Uni' will be found, otherwise it will only match exactly "Uni".
Also, put your console.log(unisWithUni); after the for loop.
var graduates = [{ id: 4, first_name: "Modestine", university: "International Medical & Technological University", email: "mdolder3#symantec.com" },
{ id: 5, first_name: "Chick", university: "Sultan Salahuddin Abdul Aziz Shah Polytechnic", email: "camorts4#google.com.au" },
{ id: 6, first_name: "Jakob", university: "Fachhochschule Rosenheim, Hochschule für Technik und Wirtschaft", email: "jharken5#spiegel.de" },
{ id: 7, first_name: "Robbi", university: "Salem University", email: "rbrister6#redcross.org" },
{ id: 8, first_name: "Colline", university: "Coastal Carolina University", email: "cbrosh7#alibaba.com" },
{ id: 9, first_name: "Michail", university: "Universidad Católica de Ávila", email: "mrome8#shinystat.com" },
{ id: 10, first_name: "Hube", university: "Universitat Rovira I Virgili Tarragona", email: "hlethbrig9#foxnews.com" }]
const unisWithUni = [];
for (let i = 0; i < graduates.length; i++) {
if (graduates[i].university.includes("Uni")) {
unisWithUni.push(graduates[i]);
}
}
console.log(unisWithUni);
You are comparing a complete string. In javascript (or almost any language) "equal" don't means "contains". So "hi" === "hi what's up" is not the same, they are not equal.
In JavasSript you want to look for indexOf() (old&new browsers) or includes() (new browsers), so:
var graduates = [
{ id: 4, first_name: "Modestine", university: "International Medical & Technological University", email: "mdolder3#symantec.com" },
{ id: 5, first_name: "Chick", university: "Sultan Salahuddin Abdul Aziz Shah Polytechnic", email: "camorts4#google.com.au" },
{ id: 6, first_name: "Jakob", university: "Fachhochschule Rosenheim, Hochschule für Technik und Wirtschaft", email: "jharken5#spiegel.de" },
{ id: 7, first_name: "Robbi", university: "Salem University", email: "rbrister6#redcross.org" },
{ id: 8, first_name: "Colline", university: "Coastal Carolina University", email: "cbrosh7#alibaba.com" },
{ id: 9, first_name: "Michail", university: "Universidad Católica de Ávila", email: "mrome8#shinystat.com" },
{ id: 10, first_name: "Hube", university: "Universitat Rovira I Virgili Tarragona", email: "hlethbrig9#foxnews.com"}
];
const unisWithUni = [];
for (let i = 0; i < graduates.length; i++) {
if (graduates[i].university.indexOf("Uni") > -1) {
unisWithUni.push(graduates[i]);
}
}
console.log(unisWithUni);
Here is an example that uses jQuery's map(). Why, just because.
Note that I convert the university to lowercase before searching for the string uni making the search case insensitive.
var graduates = [{
id: 4,
first_name: "Modestine",
university: "International Medical & Technological University",
email: "mdolder3#symantec.com"
},
{
id: 5,
first_name: "Chick",
university: "Sultan Salahuddin Abdul Aziz Shah Polytechnic",
email: "camorts4#google.com.au"
},
{
id: 6,
first_name: "Jakob",
university: "Fachhochschule Rosenheim, Hochschule für Technik und Wirtschaft",
email: "jharken5#spiegel.de"
},
{
id: 7,
first_name: "Robbi",
university: "Salem University",
email: "rbrister6#redcross.org"
},
{
id: 8,
first_name: "Colline",
university: "Coastal Carolina University",
email: "cbrosh7#alibaba.com"
},
{
id: 9,
first_name: "Michail",
university: "Universidad Católica de Ávila",
email: "mrome8#shinystat.com"
},
{
id: 10,
first_name: "Hube",
university: "Universitat Rovira I Virgili Tarragona",
email: "hlethbrig9#foxnews.com"
}
];
var unisWithUni = $.map(graduates, grad => {
return grad.university.toLowerCase().includes("uni") ? grad : null;
});
console.log(unisWithUni);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Why are these objects not equal?

I am trying to write a test in JavaScript using Mocha and Chai. At the end of the test, I want to compare 2 JavaScript objects, these should be equal.
The output I get from the test is the following:
{ publication:
{ publication_id: 'pubFetch1',
title: 'Publication Fetcher',
person_id: 'uploader',
URL: 'http://www.pubfetchertest.com',
publication_year: '2015',
upload_date: '2015-05-05 00:00:00',
page_count: '5',
type: 'paper',
rating: '0',
votes: '0',
abstract: 'Testing the Publication Fetcher',
location: 'location' },
comments:
[ { commentID: 'comment1',
personID: 'uploader',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 10:24:36',
reactions: [],
myComment: true },
{ commentID: 'comment2',
personID: 'author1',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 11:01:45',
reactions: [Object],
myComment: false } ],
keywords: [ 'keyword1', 'keyword2', 'keyword3' ],
uploader: { person_id: 'uploader', first_name: 'First', last_name: 'Last' },
score: 5,
authors:
[ { person_id: 'author1', first_name: 'First', last_name: 'Last' },
{ person_id: 'author2', first_name: 'First', last_name: 'Last' },
{ person_id: 'author3', first_name: 'First', last_name: 'Last' } ],
editors: [],
publishers: [] }
While the object I want to compare it with, is the following:
{ publication:
{ publication_id: 'pubFetch1',
title: 'Publication Fetcher',
person_id: 'uploader',
url: 'http://www.pubfetchertest.com',
publication_year: '2015',
upload_date: '2015-05-05 00:00:00',
page_count: '5',
type: 'paper',
rating: '0',
votes: '0',
abstract: 'Testing the Publication Fetcher',
location: 'location'},
comments:
[{ commentID: 'comment1',
personID: 'uploader',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 10:24:36',
reactions: [],
myComment: true},
{ commentID: 'comment2',
personID: 'author1',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 11:01:45',
reactions: [{ commentID: 'comment3',
personID: 'author2',
firstName: 'First',
lastName: 'Last',
text: 'Comment Content',
time: '2015-05-05 11:02:10',
reactions: [],
replyID: 'comment2',
myComment: false}],
myComment: false}],
keywords: ['keyword1', 'keyword2', 'keyword3'],
uploader: {person_id: 'uploader',
first_name: 'First',
last_name: 'Last'},
score: 5,
authors: [{person_id: 'author1',
first_name: 'First',
last_name: 'Last'},
{person_id: 'author2',
first_name: 'First',
last_name: 'Last'},
{person_id: 'author3',
first_name: 'First',
last_name: 'Last'}],
editors: [],
publishers: []
};
I don't see any difference in these 2 objects, so why does JavaScript say these are different? I am using JSON.stringify(obj1) === JSON.stringify(obj2) to compare these 2 objects.
JSFiddle: http://jsfiddle.net/9akeh8bh/4/
There are differences between the two objects; some keys have underscores and some are uppercase.
Have you tried standardising the key names and seeing if the comparison works?
Your reactions are different, some contain Objects, some do not.

Categories