Sort Numbers after Letters in Angular - angularjs

I want to sort Letters first and followed by numbers like below:
[Austria , France , Germany , 101110 , 124563]
This is what i have tried:
obj.sort((a,b) => a.text > b.text ? 1 : -1)
But it is sorting numbers first and then letters.
Any help?

If you are looking for a solution like you want to sort string at the first portion of array and numbers at the last of array, just make sure that you are following this procedure.
Never compare a string with a number.
If both a and b are string or both are numbers just compare both with a > b and return 1 or -1 depending on the result of comparision.
The last else block corresponds to the comparision between a number and a string. The return value determines the location of the numbers in the array. If either one of them is not a number, return -1 or 1 depending on the requirement. Since you want the numbers at the end of your array, return -1 if the value is not a number. If you send 1 instead, the numbers will take the first posion in he output array.
const data = [101110 , 124563 , 'France' , 'Austria', 'Germany'];
const output = data.sort((a,b) => {
if (
(isNaN(a) && isNaN(b)) || (!isNaN(a) && !isNaN(b))
) {
// Both are strings
// OR
// Both are numbers
return a > b ? 1 : -1;
}
else {
// One of them is a number
return isNaN(a) ? -1 : 1;
}
});
console.log(output);
Much Simplified version
const data = [101110, 'France', 'Austria', 124563, 'Germany'];
const checkOfSamePattern = (a, b) => (isNaN(a) && isNaN(b)) || (!isNaN(a) && !isNaN(b));
const output = data.sort((a, b) => checkOfSamePattern(a, b) ? a > b ? 1 : -1 : isNaN(a) ? -1 : 1);
console.log(output);

Related

How can I use my plotted data in further calculations?

So I have this code that draws zigzag-alike line
indicator("Custom zigzag", overlay=true)
bullish(at) => open[at] < close[at]
bearish(at) => open[at] > close[at]
break_up() =>
if close != open
at = 1
while close[at] == open[at]
at += 1
if bearish(at) and bullish(0)
true
else
false
else
false
break_down() =>
if close != open
at = 1
while close[at] == open[at]
at += 1
if bearish(0) and bullish(at)
true
else
false
else
false
u = break_up()
d = break_down()
plot(u?open[0] : d?open[0] : na, color = color.fuchsia, linewidth = 1, style = plot.style_line, offset=0)
I want to use the result in some further calculations, but I dont get it, how can I put the whole u?open[0] : d?open[0] : na in an array?
Roughly pushing values to an array variable leads to recalculation on each bar, IMO.
Or can I access somehow my own previous plot, since custom script call is not possible?
There are two ways to do it depending on do you want na values as it is or previous calculated values in place of na. You can save the whole thing in a variable and then use that to calculate anything like sma etc. First way
//Keeping na value
val=u?open[0] : d?open[0] : na
s=ta.sma(val,10)
plot(s)
Second way
//Replacing na values with previous values
var val=open[0]
val:=u?open[0] : d?open[0] : val[1]
s=ta.sma(val,10)
plot(s)

Merge random elements of array/split into chunks

How can I split array into chunks with some special algorithm? E.g. I need to shorten array to the size of 10 elements. If I have array of 11 elements, I want two next standing elements get merged. If I have array of 13 elements, I want three elements merged. And so on. Is there any solution?
Sample #1
var test = ['1','2','3','4','5','6','7','8','9','10','11'];
Need result = [['1'],['2'],['3'],['4'],['5|6'],['7'],['8'],['9'],['10'],['11']]
Sample #2
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13'];
Need result = [['1|2'],['3'],['4'],['5'],['6'],['7|8'],['9'],['10'],['11'],['12|13']]
Thank you in advance.
The following code most probably does what you want.
function condense(a){
var source = a.slice(),
len = a.length,
excessCount = (len - 10) % 10,
step = excessCount - 1 ? Math.floor(10/(excessCount-1)) : 0,
groupSize = Math.floor(len / 10),
template = Array(10).fill()
.map((_,i) => step ? i%step === 0 ? groupSize + 1
: i === 9 ? groupSize + 1
: groupSize
: i === 4 ? groupSize + 1
: groupSize);
return template.map(e => source.splice(0,e)
.reduce((p,c) => p + "|" + c));
}
var test1 = ['1','2','3','4','5','6','7','8','9','10','11'],
test2 = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21'];
console.log(condense(test1));
console.log(condense(test2));
A - Find the difference and create thus many random numbers for merge and put in array
B - loop through initial numbers array.
B1 - if iterator number is in the merge number array (with indexOf), you merge it with the next one and increase iterator (to skip next one as it is merged and already in results array)
B1 example:
int mergers[] = [2, 7, 10]
//in loop when i=2
if (mergers.indexOf(i)>-1) { //true
String newVal = array[i]+"|"+array[i+1]; //will merge 2 and 3 to "2|3"
i++; //adds 1, so i=3. next loop is with i=4
}
C - put new value in results array
You can try this code
jQuery(document).ready(function(){
var test = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
var arrays = [];
var checkLength = test.length;
var getFirstSet = test.slice(0,10);
var getOthers = test.slice(10,checkLength);
$.each( getFirstSet, function( key,value ) {
if(key in getOthers){
values = value +'|'+ getOthers[key];
arrays.push(values);
}else{
arrays.push(value);
}
});
console.log(arrays);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

AWK: How to load a file into array and store the final results into another array

I have an input file with the below content
child, parent, val
1 , 0 , a
2 , 1 , b
3 , 1 , c
4 , 2 , d
5 , 2 , e
I need to store them in an array named data_array by directly reading from the file without the header. Something like this
BEGIN {
while (getline < "input")
{
split($0,ft,",");
child=ft[1];
parent=ft[2];
value=ft[3];
#need help here in assigning two values into the array
data_array[child]=parent,value;
}
close("input");
}
The result_array holds the parent to child relationship with ordering.
result_array[parent]="all children separated by comma"
For example, parent 0 has one child called 1. Parent 1 has two children called 2, and 3.
The order of 2 and 3 are determined by alphabetically sorting the corresponding values.
Since the sorting of values results in b followed by c the array element should have 2,3.
There could be any number of children.
Childless nodes must be written with blank content.
These results must go into the final array in the following format.
Need help on this part to convert the data_array into the result_array
result_array["0"] = "1"
result_array["1"] = "2,3"
result_array["2"] = "4,5"
result_array["3"] = ""
result_array["4"] = ""
result_array["5"] = ""
Please shout if this is unclear.
With GNU awk for true multi-dimensional arrays and sorted_in:
$ cat tst.awk
BEGIN { FS=" *, *" }
NR==1 { for (i=1;i<=NF;i++) f[$i]=i; next }
{ parentsChildren2Vals[$(f["parent"])][$(f["child"])] = $(f["val"]) }
END {
for (parent in parentsChildren2Vals) {
PROCINFO["sorted_in"] = "#val_str_asc"
for (child in parentsChildren2Vals[parent]) {
parents2children[parent] = (parent in parents2children ?
parents2children[parent] "," : "") child
children[child]
}
}
for (child in children) {
parents2children[child]
}
PROCINFO["sorted_in"] = "#ind_num_asc"
for (parent in parents2children) {
printf "parents2children[\"%s\"] = \"%s\"\n", parent, parents2children[parent]
}
}
$ awk -f tst.awk file
parents2children["0"] = "1"
parents2children["1"] = "2,3"
parents2children["2"] = "4,5"
parents2children["3"] = ""
parents2children["4"] = ""
parents2children["5"] = ""

What does this function do reacjs

This code is come from FB ReactNative Movies Demo
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
what is means ": string" , is return a string ?
This syntax is for the flow type checker. In the argument list you have (score: number) which means the first argument of the function must be a number. After the argument list is the return value of the function. Which is declared as a string.
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
var x: string = getTextFromScore(5);
Flow is pretty smart, though, so we could remove most of these annotations.
// in no situation will this function not return a string
function getTextFromScore(score: number) {
return score > 0 ? score + '%' : 'N/A';
}
// thus, in no situation will x not be a string
var x = getTextFromScore(5);
I like to type the arguments and return value of a function, but usually not the variables unless I think it adds something, either technically or for readability.
It means the function returns a string.
Yes this means this method will return a string value..
if score is greater then 0 return value by concatenating % with it or return 'NA' when value is less then or equal to 0
function getTextFromScore(score: number): string {
return score > 0 ? score + '%' : 'N/A';
}
function takes score of type number and returns a string
then
if(score > 0 ){score + '%' }else{'N/A'}

Evaluating equality in perl using elements taken from an array ref

I have a small perl script that needs to evaluate the equality of two parameters and a small return from the database.
my ($firstId, $secondId, $firstReturnedId, $secondReturnedId, $picCount);
my $pics = $dbh->prepare(qq[select id from pictures limit 10]);
$firstId = q->param('firstId');
$secondId = q->param('secondId');
$pics->execute or die;
my $picids = $pics->fetchall_arrayref;
$picCount = scalar(#{$picids});
$firstReturnedId = $picCount > 0 ? shift(#{$picids}) : 0;
$secondReturnedId = $picCount > 1 ? pop(#{$picids}) : $firstReturnedId;
Here, a quick look at my debugger shows that $picCount = 1 and $firstReturnedId = 9020 and $secondReturnedId = 9020. However, they are both denoted as
ARRAY(0x9e79184)
0 9020
in the debugger so when I perform the final check
my $result = (($firstId == $firstReturnedId) && ($secondId == $secondReturnedId)) ? 1 : 0;
I get $result = 0, which is not what I want.
What am I doing wrong?
DBI::fetchall_arrayref returns a reference to a list of "row results". But since there could be more than one value in a row result (e.g., your query could have been select id,other_field from pictures), each row result is also a reference to a list. This means you have one more dereferencing to do in order to get the result you want. Try:
$picCount = scalar(#{$picids});
if ($picCount > 0) {
my $result = shift #{$picids};
$firstReturnedId = $result->[0];
} else {
$firstReturnedId = 0;
}
if ($picCount > 1) {
my $result = pop #{$picids};
$secondReturnedId = $result->[0];
} else {
$secondReturnedId = $firstReturnedId;
}
or if you still want to use a concise style:
$firstReturnedId = $picCount > 0 ? shift(#{$picids})->[0] : 0;
$secondReturnedId = $picCount > 1 ? pop(#{$picids})->[0] : $firstReturnedId;

Resources