I would like to know if it's possible to change the data type for a column. For instance, the json data passed to the grid are strings, but I would like slickgrid to consider it as integers or floats to be able to sort it correctly.
var data = [{"NOM": "Saguenay - Lac-Saint-Jean", "CODE": "02", "id": "0", "integer": "1"},]
I would like the 'integer' column to be an int not a string, without changing the data itself.
Thank you for your help.
As I mentioned in my comment, you are looking at the wrong place (no offense); there is no need to change datatype as actually this will not fix your problem with sort, since the SlickGrid default sort is string sort. But you could use custom sort to fix your problem.
So here is the solution: Define sort function and use them as needed. Here is a list of custom sort functions you could create:
function sorterStringCompare(a, b) {
var x = a[sortcol], y = b[sortcol];
return sortdir * (x === y ? 0 : (x > y ? 1 : -1));
}
function sorterNumeric(a, b) {
var x = (isNaN(a[sortcol]) || a[sortcol] === "" || a[sortcol] === null) ? -99e+10 : parseFloat(a[sortcol]);
var y = (isNaN(b[sortcol]) || b[sortcol] === "" || b[sortcol] === null) ? -99e+10 : parseFloat(b[sortcol]);
return sortdir * (x === y ? 0 : (x > y ? 1 : -1));
}
function sorterRating(a, b) {
var xrow = a[sortcol], yrow = b[sortcol];
var x = xrow[3], y = yrow[3];
return sortdir * (x === y ? 0 : (x > y ? 1 : -1));
}
function sorterDateIso(a, b) {
var regex_a = new RegExp("^((19[1-9][1-9])|([2][01][0-9]))\\d-([0]\\d|[1][0-2])-([0-2]\\d|[3][0-1])(\\s([0]\\d|[1][0-2])(\\:[0-5]\\d){1,2}(\\:[0-5]\\d){1,2})?$", "gi");
var regex_b = new RegExp("^((19[1-9][1-9])|([2][01][0-9]))\\d-([0]\\d|[1][0-2])-([0-2]\\d|[3][0-1])(\\s([0]\\d|[1][0-2])(\\:[0-5]\\d){1,2}(\\:[0-5]\\d){1,2})?$", "gi");
if (regex_a.test(a[sortcol]) && regex_b.test(b[sortcol])) {
var date_a = new Date(a[sortcol]);
var date_b = new Date(b[sortcol]);
var diff = date_a.getTime() - date_b.getTime();
return sortdir * (diff === 0 ? 0 : (date_a > date_b ? 1 : -1));
}
else {
var x = a[sortcol], y = b[sortcol];
return sortdir * (x === y ? 0 : (x > y ? 1 : -1));
}
}
and then in your columns definition you would use whichever custom filter you need, in your case the sorterNumeric() is what you're looking for...so your columns definition would look like the following (custom filter are at the end):
var columns = [
{id:"column1", name:"column1", field: "Column String", width:40, sortable:true, sorter:sorterStringCompare},
{id:"column2", name:"column2", field: "Column integer", width:40, sortable:true, sorter:sorterNumeric},
{id:"column3", name:"column3", field: "Column rating", width:40, sortable:true, sorter:sorterRating}
];
Saguenay...? Quebecois? :)
EDIT
I forgot to add the piece of code that attach the new sorter property to the onSort event (of course without it then it won't work), make sure you have same object name for grid and dataView, correct to whatever your variables naming are (if need be), here is the code:
grid.onSort.subscribe(function (e, args) {
var cols = args.sortCols;
dataView.sort(function (dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
sortdir = cols[i].sortAsc ? 1 : -1;
sortcol = cols[i].sortCol.field;
var result = cols[i].sortCol.sorter(dataRow1, dataRow2); // sorter property from column definition comes in play here
if (result != 0) {
return result;
}
}
return 0;
});
args.grid.invalidateAllRows();
args.grid.render();
});
You could also put your code directly into the last onSort.subscribe but I suggest having the sorter into a separate function since it is cleaner (which is the code I sent).
I used this to sort the numbers correctly.
grid.onSort.subscribe(function(e, args) {
var cols = args.sortCols;
data.sort(function(dataRow1, dataRow2) {
for (var i = 0, l = cols.length; i < l; i++) {
var result = sortOnString(cols, i, dataRow1, dataRow2);
if (result != 0) {
return result;
}
}
return 0;
});
grid.invalidate();
grid.render();
});
function sortOnString(cols, i, dataRow1, dataRow2) {
var field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
console.log("name filed " + field);
if (field === 'Folio' || field === 'Orden') {
var value1 = parseInt(dataRow1[field]),
value2 = parseInt(dataRow2[field]);
console.log("name value 1 " + value1 + "name value 2 " + value2);
} else {
var value1 = dataRow1[field],
value2 = dataRow2[field];
}
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
return result;
}
Related
I want to write a function that inserts dashes (' - ') between each two odd numbers and inserts asterisks (' * ') between each two even numbers. For instance:
Input: 99946
Output: 9-9-94*6
Input: 24877
Output: 2*4*87-7
My try
function dashAst (para) {
let stringArray = para.toString().split('');
let numbArray = stringArray.map(Number);
for (let i = 0; i<numbArray.length; i++) {
if (numbArray[i] %2 === 0 && numbArray[i+1] % 2 === 0) {
numbArray.splice(numbArray.indexOf(numbArray[i]), 0, '*')
}
else if (numbArray[i] %2 !== 0 && numbArray[i+1] %2 !== 0) {
numbArray.splice(numbArray.indexOf(numbArray[i]), 0, '-')
}
}
return numbArray
}
When I try to invoke the function it returns nothing. For instance, I tested the splice-command separately and it seems to be correct which makes it even more confusing to me. Thanks to everyone reading, or even helping a beginner out.
Looping through an Array that changes its length during the loop can be very messy (i needs to be adjusted every time you splice). It's easier to create a new result variable:
function dashAst(para) {
const stringArray = para.toString().split('');
const numbArray = stringArray.map(Number);
let result = "";
for (let i = 0; i < numbArray.length; i++) {
const n = numbArray[i], next = numbArray[i + 1];
result += n;
if (n % 2 == next % 2) {
result += n % 2 ? '-' : '*';
}
}
return result;
}
console.log(dashAst(99946)); // "9-9-94*6"
console.log(dashAst(24877)); // "2*4*87-7"
You could map the values by checking if the item and next item have the same modulo and take a separator which is defined by the modulo.
function dashAst(value) {
return [...value.toString()]
.map((v, i, a) => v % 2 === a[i + 1] % 2 ? v + '*-'[v % 2] : v)
.join('');
}
console.log(dashAst(99946)); // 9-9-94*6
console.log(dashAst(24877)); // 2*4*87-7
I hope this helps
var str = '24877';
function dashAst (para) {
let stringArray = para.toString().split('');
let numbArray = stringArray.map(x => parseInt(x));
console.log(numbArray);
var out=[];
for(let i = 0; i < numbArray.length; i++) {
if(numbArray[i] % 2 == 0){
out.push(numbArray[i]);
numbArray[i + 1] % 2 == 0 ? out.push('*') : 0;
}else if(numbArray[i] % 2 != 0) {
out.push(numbArray[i]);
numbArray[i + 1] != undefined ? out.push('-') : 0;
}
}
console.log(out.join(''));
return out;
}
dashAst(str);
I'm trying to transform an array of numbers such that each number has only one nonzero digit.
so basically
"7970521.5544"
will give me
["7000000", "900000", "70000", "500", "20", "1", ".5", ".05", ".004", ".0004"]
I tried:
var j = "7970521.5544"
var k =j.replace('.','')
var result = k.split('')
for (var i = 0; i < result.length; i++) {
console.log(parseFloat(Math.round(result[i] * 10000) /10).toFixed(10))
}
Any ideas, I'm not sure where to go from here?
Algorithm:
Split the number in two parts using the decimal notation.
Run a for loop to multiply each digit with the corresponding power of 10, like:
value = value * Math.pow(10, index); // for digits before decimal
value = value * Math.pow(10, -1 * index); // for digits after decimal
Then, filter the non-zero elements and concatenate both the arrays. (remember to re-reverse the left-side array)
var n = "7970521.5544"
var arr = n.split('.'); // '7970521' and '5544'
var left = arr[0].split('').reverse(); // '1250797'
var right = arr[1].split(''); // '5544'
for(let i = 0; i < left.length; i++)
left[i] = (+left[i] * Math.pow(10, i) || '').toString();
for(let i = 0; i < right.length; i++)
right[i] = '.' + +right[i] * Math.pow(10, -i);
let res = left.reverse() // reverses the array
.filter(n => !!n)
// ^^^^^^ filters those value which are non zero
.concat(right.filter(n => n !== '.0'));
// ^^^^^^ concatenation
console.log(res);
You can use padStart and padEnd combined with reduce() to build the array. The amount you want to pad will be the index of the decimal minus the index in the loop for items left of the decimal and the opposite on the right.
Using reduce() you can make a new array with the padded strings taking care to avoid the zeroes and the decimal itself.
let s = "7970521.5544"
let arr = s.split('')
let d_index = s.indexOf('.')
if (d_index == -1) d_index = s.length // edge case for nums with no decimal
let nums = arr.reduce((arr, n, i) => {
if (n == 0 || i == d_index) return arr
arr.push((i < d_index)
? n.padEnd(d_index - i, '0')
: '.' + n.padStart(i - d_index, '0'))
return arr
}, [])
console.log(nums)
You could split your string and then utilize Array.prototype.reduce method. Take note of the decimal position and then just pad your value with "0" accordingly. Something like below:
var s = "7970521.5544";
var original = s.split('');
var decimalPosition = original.indexOf('.');
var placeValues = original.reduce((accum, el, idx) => {
var f = el;
if (idx < decimalPosition) {
for (let i = idx; i < (decimalPosition - 1); i++) {
f += "0";
}
accum.push(f);
} else if (idx > decimalPosition) {
let offset = Math.abs(decimalPosition - idx) - 2;
for (let i = 0; i <= offset; i++) {
f = "0" + f;
}
f = "." + f;
accum.push(f);
}
return accum;
}, []);
console.log(placeValues);
Shorter alternative (doesn't work in IE) :
var s = "7970521.5544"
var i = s.split('.')[0].length
var a = [...s].reduce((a, c) => (i && +c && a.push(i > 0 ?
c.padEnd(i, 0) : '.'.padEnd(-i, 0) + c), --i, a), [])
console.log( a )
IE version :
var s = "7970521.5544"
var i = s.split('.')[0].length
var a = [].reduce.call(s, function(a, c) { return (i && +c && a.push(i > 0 ?
c + Array(i).join(0) : '.' + Array(-i).join(0) + c), --i, a); }, [])
console.log( a )
function standardToExpanded(n) {
return String(String(Number(n))
.split(".")
.map(function(n, i) {
// digits, decimals..
var v = n.split("");
// reverse decimals..
v = i ? v.reverse() : v;
v = v
.map(function(x, j) {
// expanded term..
return Number([x, n.slice(j + 1).replace(/\d/g, 0)].join(""));
})
.filter(Boolean); // omit zero terms
// unreverse decimals..
v = i ? v.map(function(x) {
return '.' + String(x).split('').reverse().join('')
}).reverse() : v;
return v;
})).split(',');
}
console.log(standardToExpanded("7970521.5544"));
// -> ["7000000", "900000", "70000", "500", "20", "1", ".5", ".05", ".004", ".0004"]
This looks like something out of my son's old 3rd Grade (core curriculum) Math book!
I'm working with an API that returns nothing but strings in the response. I need to format any decimal value returned in the string to have a leading zero but no trailing zeros. If the value is anything other than a float in the string it should be returned with out any formatting changes.
Example: if the value is ".7", ".70" or "0.70" my function will always return "0.7". If the value is "1+" it will return "1+".
Initially I thought the API was returning floats so I was doing this below. The places param is how many decimal places to display.
function setDecimalPlace(input, places) {
if (isNaN(input)) return input;
var factor = "1" + Array(+(places > 0 && places + 1)).join("0");
return Math.round(input * factor) / factor;
};
How can I accomplish what the above function is doing when the value is a decimal string, but just return the inputed value if the string does not contain a float? As an aside I'm using Angular and will end up making this a filter.
UPDATE #2
Also from https://stackoverflow.com/a/3886106/4640499
function isInt(n) {
return n % 1 === 0;
}
So at the end you could check if isFloat then isInt then conclude that it's a String.
As you said (comment) in case of '7.0':
var v = '7.0';
var formatted = (isFloat(v) || isInt(parseFloat(v))) ? parseFloat(v) : v;
UPDATE
Actually, there's no need of numberFormat function:
var v = '.7';
if(isFloat(v)) var formatted = parseFloat(v);
Take these functions:
function isFloat(n) {
n = parseFloat(n);
// from https://stackoverflow.com/a/3886106/4640499
return n === Number(n) && n % 1 !== 0;
}
function numberFormat(e, t, n, o) {
// from http://phpjs.org/functions/number_format/
var r = e,
u = isNaN(t = Math.abs(t)) ? 2 : t,
c = void 0 == n ? '.' : n,
a = void 0 == o ? ',' : o,
l = 0 > r ? '-' : '',
d = parseInt(r = Math.abs(+r || 0).toFixed(u)) + '',
s = (s = d.length) > 3 ? s % 3 : 0
;
return l + (s ? d.substr(0, s) + a : '') +
d.substr(s).replace(/(\d{3})(?=\d)/g, '$1' + a) +
(u ? c + Math.abs(r - d).toFixed(u).slice(2) : '');
}
function formatFloat(e) {
return numberFormat(e, 1);
}
And then:
var v = '.7';
console.info(isFloat(v));
console.info(formatFloat(v));
if(isFloat(v)) formatFloat(v);
I'm populating a few drop downs from some JSON, it works as expected at the moment but i'm trying to sort the values in the drop downs. For all my drop downs it works fine, except for one of them which has numbers in, in which case it lists it 1, 10, 12, 2.
Any ideas how i can keep it sorting alphabetically for everything else but get the sort to work with the numeric values too?
Here's my JS (this replicates for each field - probably should try to find a way to make this reuseable):
var populateGenres = _.map(data.genres, function (val) {
return '<option>' + val + '</option>';
}).join();
var target = '#genreField';
$('#genreField').html(populateGenres);
reArrangeSelect(target);
Here's the sort JS:
function reArrangeSelect(target) {
$(target).html($(target + " option").sort(function(a, b) {
return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
}))
}
My HTML is in this format:
<td>
<select id="genreField" class="form-control"></select>
</td>
<td>
<select id="authorField" class="form-control"></select>
</td>
function reArrangeSelect(target) {
$(target).html($(target + " option").sort(function(a, b) {
// u can use that 'getValue' function
// for "a.text == 'some string'" it will return 'some string' (string type),
// for "a.text == '10'" it will return 10 (number type)
var aVal = getValue(a.text);
var bVal = getValue(b.text);
return aVal == bVal ? 0 : aVal < bVal ? -1 : 1;
}));
}
function getValue(val) {
var asNumber = parseFloat(val);
return isNaN(asNumber) ? val : asNumber;
}
You can sort data.genres before running it through the _.map functions:
data.genres.sort(function (a, b) {
a = parseInt(a, 10);
b = parseInt(b, 10);
if(a > b) {
return 1;
} else if(a < b) {
return -1;
} else {
return 0;
}
});
Once you sort the data then run your _.map snippet:
var populateGenres = _.map(data.genres, function (val) {
return '<option>' + val + '</option>';
}).join();
All of your options should now be sorted before you append them to the <select>.
DEMO
I wrote a program in JavaScript that gathers input from user and sorts it alphabetically or if numbers alphanumerically. It's uses an array and sorts that array but JavaScript only sorts it by the first character in the number or word. So if 22, 1, and 3 was entered, it would sort it by 1,22,3 because of being sorted by first character. The same goes with words. How would I get past this? If you think my code would help you tell me how, here you go.
var input = null;
var words = new Array();
function startApp()
{
alert("Welcome to Word/Number Sorter 1.0");
alert("Enter one word/number at a time in the next prompts. Enter passw0rd to finish/stop.");
do {
input = prompt("Enter word...enter passw0rd to exit.");
if ( input != "passw0rd" ){
words.push(input);
}
else{
break;
}
}while( input != "passw0rd" );
var newW = words.sort();
for ( var i = 0; i < newW.length; i++ )
{
document.writeln(newW[i], "<br>");
}
}
To sort numerically you need a special sorting callback:
[22,1,3].sort(function(a, b) { return a - b })
> [1, 3, 22]
If you want "natural sorting", it goes like this:
function natcmp(a, b) {
var ra = a.match(/\D+|\d+/g);
var rb = b.match(/\D+|\d+/g);
var r = 0;
while(!r && ra.length && rb.length) {
var x = ra.shift(), y = rb.shift(),
nx = parseInt(x), ny = parseInt(y);
if(isNaN(nx) || isNaN(ny))
r = x > y ? 1 : (x < y ? -1 : 0);
else
r = nx - ny;
}
return r || ra.length - rb.length;
}
ls = ['img35', 'img1', 'img2', 'img22', 'img3', 'img2.gif', 'foobar']
console.log(ls.sort(natcmp))
> ["foobar","img1","img2","img2.gif","img3","img22","img35"]