Sorting numbers containing commas - bootstrap-table

I am trying to sort a column of numbers using commas, eg 1,092,021. The sorting is treating the , as a decimal and sorting improperly. eg:
1,330,000
2,350,000
3
5
7,000,000
etc
Is there a way to get the comma separated numbers to sort properly?

Here is the solution #JaredT proposed:
var nums = ['1,330,000', '2,350,000', '3', '5', '7,000,000', '1,000', '100'];
nums
.map(function (n) { return parseInt(n.replace(/,/g, ''));})
.sort(function (a, b) { return a > b;})
.map(function (i) {
return String(i).split('')
.reverse()
.map(function (n, i) {
return n + (!i || (i % 3) ? '' : ',');
})
.reverse()
.join('');
});

I did the same as #vinnie-james and it works fine. I share my code.
'columns': [{
field:'Checkbox'
},{
field:'Status'
},{
field:'Price',
visible:true,
sorter: function commas(a,b){ a = parseInt(a.replace(/,/g, '')); b = parseInt(b.replace(/,/g, '')); if (a < b) return 1; if (a > b) return -1; return 0; }]

Related

Dart sort / compare nullable datetime

I'm trying to compare list of music with releaseDate. But I can retrieve music without releaseDate and when I want to sort them, I got an error.
How can I sort / compare nullable datetime and put null releaseDate to the end?
_followedMusic.sort((a, b) {
if (a.releaseDate != null && b.releaseDate != null)
return a.releaseDate.compareTo(b.releaseDate);
else
// return ??
});
Thank you
If you take a look at the documentation for compareTo:
Returns a value like a Comparator when comparing this to other. That is, it returns a negative integer if this is ordered before other, a positive integer if this is ordered after other, and zero if this and other are ordered together.
https://api.dart.dev/stable/2.10.0/dart-core/Comparable/compareTo.html
So your compareTo should just result in returning the values -1, 0 or 1 according to if the compared object should be before, the same position or after the current object.
So in your case if you want your null entries to be at the start of the sorted list, you can do something like this:
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) {
if (s1 == null && s2 == null) {
return 0;
} else if (s1 == null) {
return -1;
} else if (s2 == null) {
return 1;
} else {
return s1.compareTo(s2);
}
});
print(list); // [null, null, a, b, c]
}
Or if you want the null at the end:
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) {
if (s1 == null && s2 == null) {
return 0;
} else if (s1 == null) {
return 1;
} else if (s2 == null) {
return -1;
} else {
return s1.compareTo(s2);
}
});
print(list); // [a, b, c, null, null]
}
Or, as #lrn suggests, make the last example in a more short and efficient way (but maybe not as readable :) ):
void main() {
final list = ['b', null, 'c', 'a', null];
list.sort((s1, s2) => s1 == null
? s2 == null
? 0
: 1
: s2 == null
? -1
: s1.compareTo(s2));
print(list); // [a, b, c, null, null]
}
what about _followdMusic.map((date) => return date ?? 1900.01.01).toList().sort(...)
the date is pseudo code, not sure how to write it. This way you put all unknown dates at one of the ends of the list.
The answer of #julemand101 also can be used with the extension function.
extension DateEx on DateTime? {
int compareToWithNull(DateTime? date2) {
if (this == null && date2 == null) {
return 0;
} else if (this == null) {
return -1;
} else if (date2 == null) {
return 1;
} else {
return this!.compareTo(date2);
}
}
}

How to find out if 'map[string][][]int' has a value

Given this code:
var a map[string][][]int
var aa map[string][][]int = map[string][][]int{"a": [][]int{{10, 10}, {20, 20}}}
var bb map[string][][]int = map[string][][]int{"b": [][]int{{30, 30}, {40, 40}}}
fmt.Println(aa) // >> map[a:[[10 10] [20 20]] b:[[30 30] [40 40]]]
how do I know if '[30, 30]' is in 'aa'?
I want to check, whether 'aa' has '[30 30]'.
You'll have to iterate over the contents of your map to check whether an element is contained in that map or not.
For example:
target := []int{30, 30}
for _, v := range myMap {
for _, sub := range v {
if len(sub) == len(target) && sub[0] == target[0] && sub[1] == target[1] {
fmt.Println("yeah")
}
}
}
With myMap as aa you'll get no output, and with myMap as bb you'll get "Yeah" printed.
If your inner-most slices get longer, you should do the check step as a loop as well instead of hard-coded like that.
Maps are only indexed by key. This means its cheap and easy (ideally constant time complexity) to find a or b, but its harder to look for a value (linear time complexity).
Therefore, it's a few for loops:
func find(searchFor [][]int, m map[string][][]int) bool {
for _, v := range m {
if sliceEq(v, searchFor) {
return true
}
}
return false
}
func sliceEq(a, b [][]int) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}

Find Path to Sum - recursion

As one of the coding exercise I tried to print the path, which you will encounter to find a particular sum, in this case: 3.
The incrementing values would be 1 and 2.
Thus the shortest path to the sum would return [1,2] or [2,1].
But I can't try to put the path to an array - I have tried putting indexes through the params, but the array would be overwritten (no wonder). Could someone suggest how to tackle this problem?
const toSum = target => {
const calc = sum => {
if (sum == target) return 0;
if (sum > target) return Infinity;
const temp1 = 1 + calc(sum + 2);
const temp2 = 1 + calc(sum + 1);
return Math.min(temp1, temp2);
};
return calc(0);
};
console.log(toSum(3));
pass an array and fill it with the current added value
const toSum = target => {
const calc = (sum ,res) => {
if (sum == 0) return res
if (sum > 2) {
res.push(2)
return calc(sum-2,res)
}
res.push(1)
return calc(sum-1,res)
};
if (target <1 ) return "need to be above 1"
if (!Number.isInteger(target) ) return "need to be an integer"
return calc(target,[])
};
console.log(toSum(3));

The IN operator is provided with too many operands; number of operands: 119 dynamodb

Try to use IN operation in dynamodb but get following error. Could anyone help me with alternative solution ?
var params = {
TableName : "table_name",
FilterExpression : "id IN ("+Object.keys(profileIdObject).toString()+ ")",
ExpressionAttributeValues : profileIdObject
};
ERROR ::
{
"message": "Invalid FilterExpression: The IN operator is provided with too many operands; number of operands: 119",
"code": "ValidationException",
"time": "2018-02-13T08:48:02.597Z",
"statusCode": 400,
"retryable": false,
"retryDelay": 25.08276239472692
}
According to docs:
The maximum number of operands for the IN comparator is 100
Found here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-expression-parameters
You will need to perform the query/scan in multiple batches, in your case with 100 of Object.keys(profileIdObject).toString() in the first batch and 19 in the second batch. Then coalesce the results.
According to dynamodb documentation, the maximum number of operands for the IN comparator is 100
So you can split into many operations like :
FilterExpression : "id IN (1,2,3, ....) OR id IN (101,102,103,...) ..."
Using this function :
let getFilterExp = function (x) {
let arr = []
let currentIndex = 0
let counter = 0
let max = 99
arr[currentIndex] = {}
for (let y in x) {
if (counter < max) {
arr[currentIndex][y] = x[y]
counter++
}
else {
currentIndex++
arr[currentIndex] = {}
arr[currentIndex][y] = x[y]
counter = 0
}
}
let exp = ''
for (let i = 0; i < arr.length; i++) {
if (i == 0) {
exp += "id IN (" + Object.keys(arr[i]).toString() + ")"
}
else {
exp += " OR id IN (" + Object.keys(arr[i]).toString() + ") "
}
}
return exp
}
Where x is the profileIdObject in your case
let filterExp = getFilterExp(profileIdObject )

handlebar comparison operator inside each loop

I have two type of value on handlebar page and needs to compare the first one from second.
I can print value of following code
{{articledetails.content_writer_id}}
before writing each loop on page. Now i want to compare the value like following. but i can not get the scope of articledetails.content_writer_id in below code.
{{#each contentwriterdetails}}
{{#compare this.id "==" articledetails.content_writer_id }}
I have already registered compare helper by using this code.
handlebars.registerHelper('compare', function (lvalue, operator, rvalue, options) {
var operators, result;
if (arguments.length < 3) {
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
}
if (options === undefined) {
options = rvalue;
rvalue = operator;
operator = "===";
}
operators = {
'==': function (l, r) { return l == r; },
'===': function (l, r) { return l === r; },
'!=': function (l, r) { return l != r; },
'!==': function (l, r) { return l !== r; },
'<': function (l, r) { return l < r; },
'>': function (l, r) { return l > r; },
'<=': function (l, r) { return l <= r; },
'>=': function (l, r) { return l >= r; },
'typeof': function (l, r) { return typeof l == r; }
};
if (!operators[operator]) {
throw new Error("Handlerbars Helper 'compare' doesn't know the operator " + operator);
}
result = operators[operator](lvalue, rvalue);
if (result) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
and above helper is working fine as i have checked that.
Any help would be appreciated.
Use the parent's context path:
{{#each contentwriterdetails}}
{{#compare this.id "==" ../articledetails.content_writer_id }}

Resources