Warning: Cannot reinitialise Datatable issue - javascript

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>

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);

How to add an 'id' to json file at first line. [javascript][node.js]

I found a working script to add an id to each object;
function addId(id) {
return function iter(o) {
if ('fediverse' in o) {
o.id = id++;
}
Object.keys(o).forEach(function (k) {
Array.isArray(o[k]) && o[k].forEach(iter);
});
};
}
var data = [{"fediverse": "#username#mastodon.online", "name": "alternatenamehere", "alternate_names": "", "gender": "", "category": "", "description": "description here.", "link": "https://mastodon.online/users/username", "image": "https://files.mastodon.online/accounts/avatars/image.jpg", "language": "", "region": "", "user": true, "group": false, "creator": false, "companyOrganization": false, "project": false, "applicationSoftware": false}];
data.forEach(addId(1))
console.dir(data, {depth: null, colors: true, maxArrayLength: null});
This script outputs;
[
{
fediverse: '#username#mastodon.online',
name: 'alternatenamehere',
alternate_names: '',
gender: '',
category: '',
description: 'description here.',
link: 'https://mastodon.online/users/username',
image: 'https://files.mastodon.online/accounts/avatars/image.jpg',
language: '',
region: '',
user: true,
group: false,
creator: false,
companyOrganization: false,
project: false,
applicationSoftware: false,
id: 1
}
]
the problem is the search I use detects ids from the first line only. how can I add the id at the first line instead of the last line?

Is it possible to use D3.tree() with a dataset that includes parents instead of children?

I'm in the process of creating a family-tree using D3. My dataset is indeed hierarchical, but the root node of the tree is the child. Each "child node" contains two "parent" nodes that represents each childs two parents. Here is an example of my data.
{
name: "Morgans Jumpin Jack Flash",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "m",
parents: [
{
name: "Moganas Heart of Fire",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "f",
parents: [
{
name: "Elkhaus Ice Storm",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "m",
parents: []
},{
name: "Morganas First Love",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "f",
parents: []
},
]
},{
name: "Desperado Hogan von der Accani",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "m",
parents: [
{
name: "Jim von Aurachgrund",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "m",
parents: []
},{
name: "Heroina D. Altobella",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "f",
parents: []
},
]
},
]
}
Each node in the tree represents a Dog. The idea here is that you can see a given Dogs pedigree by going up the family tree to the parents, grand parents, etc.
Is it possible to use the given dataset with d3.tree() without modifying the data? (I know that I could probably just rename "parents" to "children", but that would be INCREDIBLY confusing to the next person who looks at the data set.)
You don't need to alter your original dataset, instead when you create the root using d3.hierarchy you can specify which property contains the "children":
var root = d3.hierarchy(data, function(d) {
return d.parents;
})
The second parameter is the "child" accessor, but you can use it to represent parents. I've just kept a left to right layout, but it would be fairly trivial to change it to a right to left layout:
var data = {
name: "Morgans Jumpin Jack Flash",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "m",
parents: [
{
name: "Moganas Heart of Fire",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "f",
parents: [
{
name: "Elkhaus Ice Storm",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "m",
parents: []
},{
name: "Morganas First Love",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "f",
parents: []
},
]
},{
name: "Desperado Hogan von der Accani",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "m",
parents: [
{
name: "Jim von Aurachgrund",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "m",
parents: []
},{
name: "Heroina D. Altobella",
imagePath: "",
description: "",
subTitle: "",
body: "",
icon: "",
iconColor: "",
gender: "f",
parents: []
},
]
},
]
}
var root = d3.hierarchy(data, function(d) {
return d.parents;
})
var width =500;
var height = 300;
var margin = {left:100,top:50,right:100,bottom:50};
var svg = d3.select("body")
.append("svg")
.attr("width",width)
.attr("height",height)
var g = svg.append("g")
.attr("transform","translate("+margin.left+","+margin.top+")");
var tree = d3.tree().size([height-margin.top-margin.bottom,width-margin.left-margin.right]);
var path = d3.linkHorizontal().x(function(d) { return d.y; }).y(function(d) { return d.x; })
var layout = tree(root);
var link = g.selectAll(null)
.data(layout.links())
.enter().append("path")
.attr("class","link")
.attr("d", path)
var text = g.selectAll(null)
.data(root.descendants())
.enter().append("text")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
.text(function(d) { return d.data.name; })
.attr("y",-15)
.attr("x",-10)
var node = g.selectAll(null)
.data(root.descendants())
.enter().append("circle")
.attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; })
.attr("class","node")
.attr("r",function(d) { return d.data.name == "" ? 0 : 8; });
path {
fill:none;
stroke: #888;
stroke-width: 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

How to segregate the value of a JavaScript objects into Array efficiently?

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);

Data table with headers and drop down both

I have a datatable, unfortunately, the table headers are replaced with drop down selects for each column.
When I try to print, it results in a bad output header for each column, since it concatenates all the values of a drop down.
How do I modify the code so, it prints the entire selected row(s) with a decent header name selected
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" charset="utf8" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/fixedheader/3.1.5/js/dataTables.fixedHeader.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.5.6/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/select/1.3.0/js/dataTables.select.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<table id="example" class="stripe compact row-border hover" width="100%"></table>
<script>
dataSet = [
["2019-02-05T08:25:08.816Z", "David", "Thorson", "AT&T", "david#gmail.com", "", "Message to be typed here", "Telephoned, Returned your call, Will call you, Quote Needed", "Paper", "Mike", "James, Mike", "", "\nMike - TESTED", "", "", ""],
["2019-02-06T15:00:56.923Z", "David", "Thorson", "AT&T", "david#gmail.com", "", "Message to be typed here", "Telephoned, Returned your call, Will call you, Quote Needed", "Paper", "Mike", "James, Mike", "", "\nMike - OK", "", "", ""],
["2019-02-06T19:39:19.476Z", "cd", "", "", "", "275-9288", "", "Quote Needed", "", "Mike", "Chris", "", "\nMike - OK", "", "", ""],
["2019-02-06T20:15:31.693Z", "Jo", "blanc", "", "", "275-6855", "call about stone", "Please call, Quote Needed", "", "Mike", "Chris", "", "\nMike - OK", "", "", ""],
["2019-02-06T23:47:47.663Z", "Dave", "bell", "", "", "285-8958", "", "Returned your call", "", "Mike", "Chris", "", "\nMike - OK", "", "", ""],
];
const dataTable = $('#example').DataTable({
data: dataSet,
dom: 'Bfrtip',
buttons: [
{
extend: 'print',
text: 'Print all',
exportOptions: {
modifier: {
selected: null
}
}
},
{
extend: 'print',
text: 'Print selected'
}
],
select: true,
ordering: false,
"pageLength": 100,
columns: [{
title: "Date"
}, {
title: "Fname"
}, {
title: "Lname"
}, {
title: "Company"
}, {
title: "Email"
}, {
title: "Phone"
}, {
title: "Message"
}, {
title: "Priority"
}, {
title: "Source"
}, {
title: "Assigned"
}, {
title: "By"
}, {
title: "Info"
}, {
title: "SMS"
}, {
title: "Completion"
}, {
title: "CRM Number"
}, {
title: "Notes"
}],
initComplete: function() {
const table = this.api();
table.columns().every(function() {
console.log($(this.header()).text())
const title = $(this.header()).text();
$(this.header()).html(`<select><option value="">${title} (All)</option></select>`);
const options = this.data().unique().sort().toArray().reduce((options, item) => options += `<option value="${item}">${item}</option>`, '');
$(this.header()).find('select').append(options);
});
}
});
$('#example').on('change', 'thead select', event => dataTable.column($(event.target).closest('th')).search($(event.target).val()).draw());
</script>
</body>
</html>

Categories

Resources