How to segregate the value of a JavaScript objects into Array efficiently? - javascript
I have this following JSON data;
data=[
{
_id: "5b377db0c97f730014b6eb12",
title: "Integrated Compute Platform - Operations Lead",
applylink:
"https://www.techgig.com/jobs/Integrated-Compute-Platform-Operations-Lead/60221",
jd: "",
companyname: "JP Morgan Chase Bank",
location: "Hyderabad/Secunderabad",
experience: "5-7 yrs",
salary: "",
type: "",
skills: "Cisco",
startdate: "",
enddate: "",
created: "",
source: "techgig",
timestamp: 1530363306.1030896,
__v: 0
},
{
_id: "5b377db0c97f730014b6eb13",
title: "angular-ui/ux",
applylink: "https://www.techgig.com/jobs/angular-ui-ux/60213",
jd: "",
companyname: "Capgemini",
location: "Pune",
experience: "6-9 yrs",
salary: "",
type: "",
skills: "UI / UX",
startdate: "",
enddate: "",
created: "",
source: "techgig",
timestamp: 1530363306.1030896,
__v: 0
},
{
_id: "5b377db0c97f730014b6eb14",
title: "BCM - Big Data CoE Lead",
applylink: "https://www.techgig.com/jobs/BCM-Big-Data-CoE-Lead/60226",
jd: "",
companyname: "Capgemini",
location: "Pune",
experience: "17-20 yrs",
salary: "",
type: "",
skills: "Big Data",
startdate: "",
enddate: "",
created: "",
source: "techgig",
timestamp: 1530363306.1030896,
__v: 0
},
{
_id: "5b377db0c97f730014b6eb15",
title: "Staff QA Engineer, Open VisaNet",
applylink:
"https://www.techgig.com/jobs/Staff-QA-Engineer-Open-VisaNet/60218",
jd: "",
companyname: "Visa",
location: "Bengaluru/Bangalore",
experience: "7-12 yrs",
salary: "",
type: "",
skills: "Erlang",
startdate: "",
enddate: "",
created: "",
source: "techgig",
timestamp: 1530363306.1030896,
__v: 0
},
{
_id: "5b377db0c97f730014b6eb16",
title: "Hadoop - Big Data Developer",
applylink:
"https://www.techgig.com/jobs/Hadoop-Big-Data-Developer/60225",
jd: "",
companyname: "Morgan Stanley",
location: "Mumbai",
experience: "4-7 yrs",
salary: "",
type: "",
skills: "Big Data",
startdate: "",
enddate: "",
created: "",
source: "techgig",
timestamp: 1530363306.1030896,
__v: 0
},
{
_id: "5b377db0c97f730014b6eb17",
title: "Specialist UX/UI Designer",
applylink:
"https://www.techgig.com/jobs/Specialist-UX-UI-Designer/60215",
jd: "",
companyname: "Hewlett Packard",
location: "Bengaluru/Bangalore",
experience: "5-9 yrs",
salary: "",
type: "",
skills: "UI / UX",
startdate: "",
enddate: "",
created: "",
source: "techgig",
timestamp: 1530363306.1030896,
__v: 0
},
{
_id: "5b377db0c97f730014b6eb18",
title: "Hadoop - Big Data Developer",
applylink:
"https://www.techgig.com/jobs/Hadoop-Big-Data-Developer/60225",
jd: "",
companyname: "Morgan Stanley",
location: "Mumbai",
experience: "4-7 yrs",
salary: "",
type: "",
skills: "Big Data",
startdate: "",
enddate: "",
created: "",
source: "techgig",
timestamp: 1530363306.1030896,
__v: 0
}]
Data is lot more than that, around 1.5 MB coming from a JSON file hosted online, this is just sample, I have to filter the jobs on the basis of location, skill, experience.
What I thought of to add everything to the state then preprocess the data in the 3 diff array with the following format
{
value: jobData.xxx,
label: jobData.xxx
}
Push the data in react-select, get from that and use a filter for the whole state and display the result in a nice UI.
The problem here is data is really huge, and no option to get chunks from backend, I have to use the full data at once.
My questions are:-
How to store the data skill, location and exp segregate in diff array without the duplicated elements, I tried with a map, duplicated element are coming. Iterating through the whole array again to check if it's not there would not be efficient?
Is there a better way you all propose to do it?
Thanks
Edit-1
So basically what i want 3 json object
var skill = {
value: jobData.skills,
label: jobData.skills
};
var location = {
value: jobData.location,
label: jobData.location
};
var experience = {
value: jobData.experience,
label: jobData.experience
};
pushed in three array:
var skillList=[];
var locationList=[];
var experienceList=[];
Which will be inturn set in react state
Edit-2
This is the whole code:
import React from "react";
import Style from "./Landing.module.scss";
import JobImage from "./2663543.jpg";
import Select from "react-select";
class LandingPage extends React.Component {
state = {
data: [
//the data mentiond above
],
skills: [],
location: [],
experience: []
};
componentDidMount() {
var skillList=[];
var locationList=[];
var experienceList=[];
this.state.data.map(jobData => {
var skill = {
value: jobData.skills,
label: jobData.skills
};
var location = {
value: jobData.location,
label: jobData.location
};
var experience = {
value: jobData.experience,
label: jobData.experience
};
});
}
render() {
return (
<>
<div className={Style.bigHead}>
<div className={Style.bigImage}>
<img src={JobImage} alt="Job Image"></img>
</div>
<div className={Style.filters}>
<Select
isMulti
name="location"
options={this.state.location}
className="basic-multi-select"
classNamePrefix="select"
/>
<Select
isMulti
name="experience"
options={this.state.experience}
className="basic-multi-select"
classNamePrefix="select"
/>
<Select
isMulti
name="skill"
options={this.state.skills}
className="basic-multi-select"
classNamePrefix="select"
/>
</div>
</div>
</>
);
}
}
export default LandingPage;
This is one way to do it
let skillsList = [...new Set(data.map(({skills}) => skills))].map(value => ({value, label:value}));
let locationList = [...new Set(data.map(({location}) => location))].map(value => ({value, label:value}));
let experienceList = [...new Set(data.map(({experience}) => experience))].map(value => ({value, label:value}));
let data=[{ _id: "5b377db0c97f730014b6eb12", title: "Integrated Compute Platform - Operations Lead", applylink: "https://www.techgig.com/jobs/Integrated-Compute-Platform-Operations-Lead/60221", jd: "", companyname: "JP Morgan Chase Bank", location: "Hyderabad/Secunderabad", experience: "5-7 yrs", salary: "", type: "", skills: "Cisco", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb13", title: "angular-ui/ux", applylink: "https://www.techgig.com/jobs/angular-ui-ux/60213", jd: "", companyname: "Capgemini", location: "Pune", experience: "6-9 yrs", salary: "", type: "", skills: "UI / UX", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb14", title: "BCM - Big Data CoE Lead", applylink: "https://www.techgig.com/jobs/BCM-Big-Data-CoE-Lead/60226", jd: "", companyname: "Capgemini", location: "Pune", experience: "17-20 yrs", salary: "", type: "", skills: "Big Data", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb15", title: "Staff QA Engineer, Open VisaNet", applylink: "https://www.techgig.com/jobs/Staff-QA-Engineer-Open-VisaNet/60218", jd: "", companyname: "Visa", location: "Bengaluru/Bangalore", experience: "7-12 yrs", salary: "", type: "", skills: "Erlang", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb16", title: "Hadoop - Big Data Developer", applylink: "https://www.techgig.com/jobs/Hadoop-Big-Data-Developer/60225", jd: "", companyname: "Morgan Stanley", location: "Mumbai", experience: "4-7 yrs", salary: "", type: "", skills: "Big Data", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb17", title: "Specialist UX/UI Designer", applylink: "https://www.techgig.com/jobs/Specialist-UX-UI-Designer/60215", jd: "", companyname: "Hewlett Packard", location: "Bengaluru/Bangalore", experience: "5-9 yrs", salary: "", type: "", skills: "UI / UX", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb18", title: "Hadoop - Big Data Developer", applylink: "https://www.techgig.com/jobs/Hadoop-Big-Data-Developer/60225", jd: "", companyname: "Morgan Stanley", location: "Mumbai", experience: "4-7 yrs", salary: "", type: "", skills: "Big Data", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }];
let skillsList = [...new Set(data.map(({skills}) => skills))].map(value => ({value, label:value}));
let locationList = [...new Set(data.map(({location}) => location))].map(value => ({value, label:value}));
let experienceList = [...new Set(data.map(({experience}) => experience))].map(value => ({value, label:value}));
console.log(skillsList);
console.log(locationList);
console.log(locationList);
Another way, which may or may not be more performant I don't know, but it iterates data once, not 3 times
let data=[{ _id: "5b377db0c97f730014b6eb12", title: "Integrated Compute Platform - Operations Lead", applylink: "https://www.techgig.com/jobs/Integrated-Compute-Platform-Operations-Lead/60221", jd: "", companyname: "JP Morgan Chase Bank", location: "Hyderabad/Secunderabad", experience: "5-7 yrs", salary: "", type: "", skills: "Cisco", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb13", title: "angular-ui/ux", applylink: "https://www.techgig.com/jobs/angular-ui-ux/60213", jd: "", companyname: "Capgemini", location: "Pune", experience: "6-9 yrs", salary: "", type: "", skills: "UI / UX", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb14", title: "BCM - Big Data CoE Lead", applylink: "https://www.techgig.com/jobs/BCM-Big-Data-CoE-Lead/60226", jd: "", companyname: "Capgemini", location: "Pune", experience: "17-20 yrs", salary: "", type: "", skills: "Big Data", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb15", title: "Staff QA Engineer, Open VisaNet", applylink: "https://www.techgig.com/jobs/Staff-QA-Engineer-Open-VisaNet/60218", jd: "", companyname: "Visa", location: "Bengaluru/Bangalore", experience: "7-12 yrs", salary: "", type: "", skills: "Erlang", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb16", title: "Hadoop - Big Data Developer", applylink: "https://www.techgig.com/jobs/Hadoop-Big-Data-Developer/60225", jd: "", companyname: "Morgan Stanley", location: "Mumbai", experience: "4-7 yrs", salary: "", type: "", skills: "Big Data", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb17", title: "Specialist UX/UI Designer", applylink: "https://www.techgig.com/jobs/Specialist-UX-UI-Designer/60215", jd: "", companyname: "Hewlett Packard", location: "Bengaluru/Bangalore", experience: "5-9 yrs", salary: "", type: "", skills: "UI / UX", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }, { _id: "5b377db0c97f730014b6eb18", title: "Hadoop - Big Data Developer", applylink: "https://www.techgig.com/jobs/Hadoop-Big-Data-Developer/60225", jd: "", companyname: "Morgan Stanley", location: "Mumbai", experience: "4-7 yrs", salary: "", type: "", skills: "Big Data", startdate: "", enddate: "", created: "", source: "techgig", timestamp: 1530363306.1030896, __v: 0 }];
let {skillsList, locationList, experienceList} = data.reduce((acc, {skills, location, experience}) => {
acc.skillsList.add(skills);
acc.locationList.add(location);
acc.experienceList.add(experience);
return acc;
}, {skillsList:new Set, locationList:new Set, experienceList:new Set});
skillsList = [...skillsList].map(value => ({value, label:value}));
locationList = [...locationList].map(value => ({value, label:value}));
experienceList = [...experienceList].map(value => ({value, label:value}));
console.log(skillsList);
console.log(locationList);
console.log(experienceList);
Related
finding common key in array of objects in javascript
let array = [ { en: "", ar: "", sp: "", fr: "" }, { en: "", ar: "", sp: "", gu: "" }, { en: "", ar: "", sp: "", hi: "" }, { en: "", ar: "", sp: "", la: "" }, { en: "", ar: "", sp: "" }, ]; I have this array of objects and want to find the common key from all objects the final output should be like let array2 =[ "en", "ar", "sp"] so the filter should only return the key's which are available in every objects. I am not able to find the best algorithm for this sorting. A little guidance will also be very helpful.
const array = [ { en: "", ar: "", sp: "", fr: "" }, { en: "", ar: "", sp: "", gu: "" }, { en: "", ar: "", sp: "", hi: "" }, { en: "", ar: "", sp: "", la: "" }, { en: "", ar: "", sp: "" }] const allKeys = [...new Set(array.flatMap(i=>Object.keys(i)))] const commonKeys = allKeys.filter(i=>!array.some(j=>!Object.keys(j).includes(i))) console.log(commonKeys)
let array = [ { en: "", ar: "", sp: "", fr: "" }, { en: "", ar: "", sp: "", gu: "" }, { en: "", ar: "", sp: "", hi: "" }, { en: "", ar: "", sp: "", la: "" }, { en: "", ar: "", sp: "" }, ]; let keysArr = array.map(x => Object.keys(x)); let commonKeys = keysArr.pop().reduce((res, x) => { const isEvery = keysArr.every((i) => i.includes(x)); if (!res.includes(x) && isEvery) { res.push(x); } return res; }, []); console.log(commonKeys);
Pretty easy to do with reduce, Object.keys, filter, and includes. First pass in reduce you just store the keys of the object. Each pass after that you are just looking for the keys that exist in the current row. let array = [ { en: "", ar: "", sp: "", fr: "" }, { en: "", ar: "", sp: "", gu: "" }, { en: "", ar: "", sp: "", hi: "" }, { en: "", ar: "", sp: "", la: "" }, { en: "", ar: "", sp: "" }, ]; const commonKeys = array.reduce((commonKeys, item, index) => { // get the keys const itemKeys = Object.keys(item); // if we are at first index, return the keys // If we are > 1, filter only the keys that are in the object return !index ? itemKeys : commonKeys.filter(key => itemKeys.includes(key)); }, []); console.log(commonKeys);
Ensure a random javascript object selection isn't selected twice
I want to store the random selection of a function in an array so that in future runs of the random function the property that was previously picked will not be selected. For example, I want it so if England is selected at random then, future runs of this function will omit England. Javascript Object var countryDataObj = { England: { Title: "England", imageUrl: "", Total: 70 }, Spain: { Title: "Spain", imageUrl: "", Total: 57 }, Wales: { Title: "Wales", imageUrl: "", Total: 52 }, Germany: { Title: "Germany", imageUrl: "", Total: 16 }, Ireland: { Title: "Ireland", imageUrl: "", Total: 14 }, Russia: { Title: "Russia", imageUrl: "", Total: 19 }, Portugal: { Title: "Portugal", imageUrl: "", Total: 32 }, Wales: { Title: "Wales", imageUrl: "", Total: 52 }, France: { Title: "France", imageUrl: "", Total: 49 } } The current randomize function function returnCountry(obj) { var keys = Object.keys(obj); return obj[keys[ keys.length * Math.random() << 0]]; };
There are many ways to do this, one would be an object-oriented approach. class CountryPicker { countries = [ { Title: "England", imageUrl: "", Total: 70 }, { Title: "Spain", imageUrl: "", Total: 57 }, { Title: "Wales", imageUrl: "", Total: 52 }, { Title: "Germany", imageUrl: "", Total: 16 }, { Title: "Ireland", imageUrl: "", Total: 14 }, { Title: "Russia", imageUrl: "", Total: 19 }, { Title: "Portugal", imageUrl: "", Total: 32 }, { Title: "Wales", imageUrl: "", Total: 52 }, { Title: "France", imageUrl: "", Total: 49 } ]; randomCountry() { if (this.countries.length == 0) throw new Error("None left"); const index = Math.floor(Math.random() * this.countries.length); const result = this.countries[index]; this.countries.splice(index, 1); return result; } } const picker = new CountryPicker(); console.log(picker.randomCountry()); Playground
Show nested array items react native
I have array of comments and their replies like this: [ { commentId: "5efd85d5b2eff7063b8ec802", description: "some comment description", isAnonymous: false, createdAt: "2020-07-02T06:59:33.317Z", currentUserLiked: 0, likes: 0, user: { firstName: "ar", lastName: "ar", email: "test#email.com", username: "sami", isVerified: false, }, children: [ { commentId: "5efd86b7b2eff7063b8ec803", parentId: "5efd85d5b2eff7063b8ec802", description: "some comment description", isAnonymous: false, createdAt: "2020-07-02T07:03:19.405Z", currentUserLiked: 0, likes: 0, user: { firstName: "ar", lastName: "ar", email: "test#email.com", username: "sami", isVerified: false, }, children: [ { commentId: "5efd89c4b2eff7063b8ec805", parentId: "5efd86b7b2eff7063b8ec803", description: "Child of Child", isAnonymous: false, createdAt: "2020-07-02T07:16:20.717Z", currentUserLiked: 0, likes: 0, user: { firstName: "ar", lastName: "ar", email: "test#email.com", username: "sami", isVerified: false, }, children: [], }, ], }, { commentId: "5efd8996b2eff7063b8ec804", parentId: "5efd85d5b2eff7063b8ec802", description: "Child of Child", isAnonymous: false, createdAt: "2020-07-02T07:15:34.341Z", currentUserLiked: 0, likes: 0, user: { firstName: "ar", lastName: "ar", email: "test#email.com", username: "sami", isVerified: false, }, children: [], }, ], }, ]; and I want to show them as all children in same level in react native using flatList. How can I do this?
Do I understand correctly?: const comments = [{id: 1, children: [{id: 2, children: [{id: 3, children:[]}]}]}]; const flatComments = (list) => { return list.flatMap(el => { const {children, ...out} = el; return [out, ...flatComments(children)]; }); }; flatComments(comments); // [{id: 1}, {id: 2}, {id: 3}];
Warning: Cannot reinitialise Datatable issue
Am using Jquery Datatable to render table. By default the page wont display any table and there's a search box on the page, on entering a value it will make a call to database and render the datatable according to the response from database. So now once the datatable is rendered, if I enter a new value in search box and call the datatable to be rendered it gives me above error. I tried bdestroy and redrawing table but nothing seems to work for me. $(document).ready(function() { var resultArray = [ ["290013", "TEST OF ENSEMBLE", "11-25-2016", "", "", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["290015", "XXX5", "10-19-2016", "test", "$33.00", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "2002", "XXX5", "XXX5", "XXX5", "", "1864", "2017", "VERSION", "23004746", "XXX5", "", "One Time", "", "", "", "", "", "", "21004482", "9189", "Feature Set", "20003880", "XXX5", "XXX5", "BASE", "19-APR-2017", "04-18-2017", "3877", "", ""], ["290015", "XXX5", "10-19-2016", "test", "$33.00", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "1865", "Deluxe", "EDITION", "", "", "", "", "", "", "", "", "", "", "", "9190", "Charge", "", "", "", "", "", "", "", "", ""] ]; console.log(JSON.stringify(resultArray)); var table = $('#example').DataTable({ columns: [{ title: 'Item Master Number', name: 'ItemMasterNumber' }, { title: 'Description', name: 'Description' }, { title: 'First Processing Date', name: 'FirstProcessingDate' }, { title: 'Alias', name: 'Alias' }, { title: 'Master Price', name: 'MasterPrice' }, { title: 'Product Id', name: 'ProductId' }, { title: 'Product Description', name: 'ProductDescription' }, { title: 'Feature Set#', name: 'FeatureSetId' }, { title: 'Feature Set Code', name: 'FeatureSetCode' }, { title: 'Feature Set Name', name: 'FeatureSetName' }, { title: 'Feature Set Description', name: 'Feature Set Description' }, { title: 'Enablement Type', name: 'Enablement Type' }, { title: 'Feature Id', name: 'FeatureId' }, { title: 'Attribute Name', name: 'AttributeName' }, { title: 'Attribute Value', name: 'AttributeValue' }], data: resultArray, rowsGroup: [ // Always the array (!) of the column-selectors in specified // order to which rows groupping is applied. // (column-selector could be any of specified in: // https://datatables.net/reference/type/column-selector) 'ItemMasterNumber:name', 'Description:name', 'FirstProcessingDate:name', 'Alias:name', 'MasterPrice:name', 'ProductId:name', 'ProductDescription:name', 'FeatureSetId:name', 'FeatureSetCode:name' ], pageLength: '20', }); }); I am calling above code each time the value is entered in the search box and clicked on a button besides it. All I want is to display the new data on the Datatable. How can I resolve this error.
Here's a JSFiddle/snippet I threw together real quick, please let me know if this helps: https://jsfiddle.net/p9pot11h/5/ var dataTable_ = null; var resultArray = [ ["290013", "TEST OF ENSEMBLE", "11-25-2016", "", "", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""], ["290015", "XXX5", "10-19-2016", "test", "$33.00", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "2002", "XXX5", "XXX5", "XXX5", "", "1864", "2017", "VERSION", "23004746", "XXX5", "", "One Time", "", "", "", "", "", "", "21004482", "9189", "Feature Set", "20003880", "XXX5", "XXX5", "BASE", "19-APR-2017", "04-18-2017", "3877", "", ""], ["290015", "XXX5", "10-19-2016", "test", "$33.00", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "1865", "Deluxe", "EDITION", "", "", "", "", "", "", "", "", "", "", "", "9190", "Charge", "", "", "", "", "", "", "", "", ""] ]; var resultArray2 = [ ["290013", "TEST OF ENSEMBLE", "11-25-2016", "", "", "22001204", "TEST EP PRODUCT FOR DEVELOPMENT", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""] ]; $(document).ready(function() { //console.log(JSON.stringify(resultArray)); dataTable_ = $('#example').DataTable({ columns: [{ title: 'Item Master Number', name: 'ItemMasterNumber' }, { title: 'Description', name: 'Description' }, { title: 'First Processing Date', name: 'FirstProcessingDate' }, { title: 'Alias', name: 'Alias' }, { title: 'Master Price', name: 'MasterPrice' }, { title: 'Product Id', name: 'ProductId' }, { title: 'Product Description', name: 'ProductDescription' }, { title: 'Feature Set#', name: 'FeatureSetId' }, { title: 'Feature Set Code', name: 'FeatureSetCode' }, { title: 'Feature Set Name', name: 'FeatureSetName' }, { title: 'Feature Set Description', name: 'Feature Set Description' }, { title: 'Enablement Type', name: 'Enablement Type' }, { title: 'Feature Id', name: 'FeatureId' }, { title: 'Attribute Name', name: 'AttributeName' }, { title: 'Attribute Value', name: 'AttributeValue' }], data: resultArray, rowsGroup: [ // Always the array (!) of the column-selectors in specified // order to which rows groupping is applied. // (column-selector could be any of specified in: // https://datatables.net/reference/type/column-selector) 'ItemMasterNumber:name', 'Description:name', 'FirstProcessingDate:name', 'Alias:name', 'MasterPrice:name', 'ProductId:name', 'ProductDescription:name', 'FeatureSetId:name', 'FeatureSetCode:name' ], pageLength: '20', }); $('#search-button').on('click', function() { var data = resultArray2; var dataToSearch = $('#search').val(); if (dataToSearch == '') { data = []; } // AJAX CALL TO GET RESULTS HERE // SUCCESS FUNCTION TO CALL INSIDE AJAX SUCCESS rePopulateTable(data); }); }); var rePopulateTable = function(data) { dataTable_.clear(); dataTable_.rows.add(data); dataTable_.draw(); }; <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script> <link href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css" rel="stylesheet" /> <body> <input type="search" id="search" placeholder="Search" /> <input type="button" id="search-button" value="Search DB" /> <br/> <br/> <br/> <table id="example"> </table> </body>
Filter objects array with keys array [inverse]
I have this following keys array: var keys = [{userId: "333"}, {userId: "334"}] And this objects array: var users = [ {id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""} ] I need to change my users Array by filter it with my keys Array[inverse result]. Cant figure it out, get all the answers! (js, jquery, angular) Anyone?
You can use filter() and find(). var users = [ {id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""} ] var keys = [{userId: "333"}, {userId: "334"}] var result = users.filter(function(o) { return !keys.find(function(e) { return e.userId == o.id }) }) console.log(result)
You can have an array of ids and then you can just check for availability in this list var users = [ {id: "333", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "334", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "335", firstName: "", lastName: "", idCard: "", birthDate: ""}, {id: "336", firstName: "", lastName: "", idCard: "", birthDate: ""} ] var keys = [{userId: "333"}, {userId: "334"}] var idList = keys.map(function(x){ return x.userId}); var r = users.filter(function(x){ return idList.indexOf(x.id) < 0 }) console.log(r)
You could use a hash table for filtering. var keys = [{ userId: "333" }, { userId: "334" }], users = [{ id: "333", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "334", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "335", firstName: "", lastName: "", idCard: "", birthDate: "" }, { id: "336", firstName: "", lastName: "", idCard: "", birthDate: "" }], filtered = users.filter(function (a) { return !this[a.id]; }, keys.reduce(function (r, a) { r[a.userId] = true; return r; }, Object.create(null))); console.log(filtered); .as-console-wrapper { max-height: 100% !important; top: 0; }