Javascript and more advanced sorting - javascript

I know there's been a lot of questions like these around the site, but I'm in a struggle and I have tried to do my homework before asking.
I have an array of objects that each have three fields. Status, Type, and Time. All are integers.
Status is between 1-9 and represents an availability and everything
is sorted by status.
Type represents if the user is 0 - "Paid" or 1 -"Free". And paid are
always above free.
this is my code for that
function sortListings(obj1, obj2) {
var statusA = obj1.status;
var statusB = obj2.status;
var typeA = obj1.type;
var typeB = obj2.type;
if (typeA == typeB) {
return (statusA < statusB) ? -1 : (statusA > statusB) ? 1 : 0;
} else {
return (typeA < typeB ) ? -1 : 1;
}
}
And this works great. Now sometimes two objects will have the same status and be in the same pay type. So I'd like, in this case, to present the latest time stamp first.
Time is stored as an int ( unix )
I don't know how to go about this. Here is my attempt :
function sortListing(obj1, obj2) {
var statusA = obj1.status;
var statusB = obj2.status;
var typeA = obj1.type;
var typeB = obj2.type;
var timeA = obj1.time;
var timeB = obj2.time;
if (typeA == typeB) { // has the same type
if (statusA == statusB) { // has the same status
return timeA - timeB; //so sort by time
} else { // different statues, same type
return (statusA < statusB) ? -1 : (statusA > statusB) ? 1 : 0; // sort by status
}
} else {
return (typeA < typeB ) ? -1 : 1;
}
}
As you can see my knowledge of the inner workings of sort is not that great.
Any articles, answers or comments are greatly appreciated.

Your main issue is fall-through to less significant fields if the higher level fields are identical. Try this:
function sortListing(obj1, obj2) {
function compareType(a, b) {
return a.type - b.type;
}
function compareStatus(a, b) {
return a.status - b.status;
}
function compareTime(a, b) {
return a.time - b.time;
}
return compareType(obj1, obj2) ||
compareStatus(obj1, obj2) ||
-compareTime(obj1, obj2); // negative to reverse order
}
The || short circuit operator will cause the second (and subsequently third) comparison to be evaluated only if the prior comparison returns 0. The sort order is trivially changed just by changing the order in which the three functions are called.
The inner functions could, of course, be exposed in a higher level scope, allowing you to use each of those comparator functions individually, or in alternate orders.
Note also how this method avoids dereferencing any of the object properties unless absolutely necessary. If you were sorting thousands of entries that can make a significant difference, although in practise that might be offset by the potential expense of making three function calls internally.... Only benchmarks can really tell.

I would structure the code differently. Compare the most significant key first, then the next most significant, and so on. Only when you've compared all keys and found them all to be equal do you return 0.
function sortListing(obj1, obj2) {
var statusA = obj1.status;
var statusB = obj2.status;
var typeA = obj1.type;
var typeB = obj2.type;
var timeA = obj1.time;
var timeB = obj2.time;
if (typeA < typeB)
return -1;
if (typeA > typeB)
return 1;
if (statusA < statusB)
return -1;
if (statusA > statusB)
return 1;
if (timeA < timeB)
return -1;
if (timeA > timeB)
return 1;
return 0;
}
Now, any time you see a piece of code that looks like the same thing repeated over and over, a light should go off in your head that something can be generalized:
function compareKeys(k1, k2) {
for (var i = 0; i < k1.length; ++i) {
if (k1[i] < k2[i]) return -1;
if (k1[i] > k2[i]) return 1;
}
return 0;
}
function sortListing(obj1, obj2) {
return compareKeys([obj1.type, obj1.status, obj1.time], [obj2.type, obj2.status, obj2.time]);
}
Another refinement:
function pluck(obj, keynames) {
var keys = [];
for (var i = 0; i < keynames.length; ++i) // could be done with .map()
keys.push(obj[keynames[i]]);
return keys;
}
function sortListing(obj1, obj2) {
var keynames = ["type", "status", "time"];
return compareKeys(pluck(obj1, keynames), pluck(obj2, keynames));
}

I couldn't resist trying out a solution that emphasizes the recursive nature of this problem. You're basically comparing two arrays like this: you compare the first elements and if the first elements are the same then you compare the rest in the same way.
Here is the function to compare the arrays (it's assuming that arrays are the same length):
function compareArray(a1,a2) {
if (a1[0]==a2[0]) {
if (a1.length==1) {
return 0;
}
else {
return compareArray(a1.slice(1),a2.slice(1));
}
}
else {
return (a1[0]<a2[0] ) ? -1 : 1;
}
}
Same function with try/catch to check length:
function compareArray(a1, a2) {
var l = a1.length;
try {
if (l != a2.length) throw "arrays have diff. size";
if (l == 0) throw "empty array";
var h1 = a1[0];
var h2 = a2[0];
if (h1 == h2) {
if (l == 1) {
return 0;
} else {
return compareArray(a1.slice(1), a2.slice(1));
}
} else {
return (h1 < h2) ? -1 : 1;
}
} catch (err) {
// handle err
}
}
Then you can compare the fields
function sortListings(obj1, obj2) {
var statusA = obj1.status;
var statusB = obj2.status;
var typeA = obj1.type;
var typeB = obj2.type;
var timeA = obj1.time;
var timeB = obj2.time;
return compareArray([statusA,typeA,timeA],[statusB,typeB,timeB])
}
Btw you can use the compareArray to compare any number of fields.

Related

Javascript find the most repetitive character occurrence from the string

Let's say we have this string:
BBBBAAAABBAAAAAACCCCCBDDDDEEEEEEE,FFF
As you can see, here B is occurring 4 times at first but B is also present before DDDD.
Similarly, A is occurring 4 times at the beginning and later 6 times.
I want the expected output if I am searching B it should 4 times as the max occurrence B is 4. However if I am searching A then it should return 6 because the most occurrence for A is 6.
Here is my code I tried:
function checkRepeatativeString(str) {
let hashMap = {};
let seen = new Set();
let counter = 1;
let maxValue = 1;
let isPreviousValueSame = false;
let isNextValueSame = true;
for (let i = 0; i < str.length; i++) {
/**
* is previous value same
*/
if (str[i] == str[i-1]) {
isPreviousValueSame = true;
}
/**
* is next value same
*/
if (str[i] == str[i+1]) {
isNextValueSame = true;
}
if (seen.has(str[i]) && isPreviousValueSame) {
hashMap[str[i]][0]++;
hashMap[str[i]][1]++;
isPreviousValueSame = false;
} else if(seen.has(str[i]) && !isNextValueSame) {
maxValue = Math.max(hashMap[str[i]][1], maxValue);
counter = 0;
hashMap[str[i]] = [counter, maxValue];
} else {
maxValue = Math.max(maxValue, counter);
seen.add(str[i]);
hashMap[str[i]] = [counter, maxValue];
isPreviousValueSame = false;
}
}
return hashMap;
}
let str = "BBBBAAAABBAAAAAACCCCCBDDDDEEEEEEE,FFF";
console.log(checkRepeatativeString(str));
This code is working but if you look for B, I am getting stuck at the beginning of value.
My program returns out for B:
B: [ 1, 1 ]
^ ^
Inside array, 1 is a counter which scans the string and second 1 in array is a max value which should return the output. However my program is returning 1 for B. I am expecting 4 as max value.
Help would be appreciated~
Quick and dirty.
function maxConsecutiveCharacters(check, haystack) {
if(check.length !== 1) return false;
let result = 0;
let buffer = 0;
for(let i = 0; i < haystack.length; i++) {
if(haystack[i] === check) {
buffer++;
}
else {
if(buffer > result) {
result = buffer;
}
buffer = 0;
}
if(buffer > result) {
result = buffer;
}
}
return result;
}
That looks overly complicated. Consider approaching the problem from a different angle - first split up the string into segments of repeating characters, and group them into an object based on the length of the longest substring for a given character.
const checkRepeatativeString = (str) => {
const longestCounts = {};
for (const consecutive of (str.match(/(.)\1*/g) || [])) {
const char = consecutive[0];
longestCounts[char] = Math.max(
longestCounts[char] || 0, // Use the existing value in the object if it exists and is higher
consecutive.length // Otherwise, use the length of the string iterated over
);
}
return longestCounts;
};
let str = "BBBBAAAABBAAAAAACCCCCBDDDDEEEEEEE,FFF";
console.log(checkRepeatativeString(str));
Simpler code often means less surface area for bugs.

Simple Sort Sample for slickgrid

I want to havesimple slickgrid column sort. however I might not understand the basic idea.
what I have done is like this.
Make column sortable
{id: "score", name: "number", field: "score",sortable: true},
Make function for sort calculation.
function sortfn(o1, o2) {
if (o1[column.field] > o2[column.field]) {
return 1;
} else if (o1[column.field] < o2[column.field]) {
return -1;
}
return 0;
}
then subsclibe to onSort.
grid.onSort.subscribe(function (e, args) {
grid.invalidateAllRows();
grid.render();
});
then next,,,,
I guess I should put sortfn somewhere though, but how??
where should I put sortfn??
Check out the examples here. There is no default sorting in the grid - this is left to the datasource to manage.
This example uses the native javascript sort property of the source data array to sort the rows:
grid = new Slick.Grid("#myGrid", data, columns, options);
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 field = cols[i].sortCol.field;
var sign = cols[i].sortAsc ? 1 : -1;
var value1 = dataRow1[field], value2 = dataRow2[field];
var result = (value1 == value2 ? 0 : (value1 > value2 ? 1 : -1)) * sign;
if (result != 0) {
return result;
}
}
return 0;
});
grid.invalidate();
grid.render();
});
This example outsources the sorting to the DataView object which is the grid's datasource.
grid.onSort.subscribe(function (e, args) {
sortdir = args.sortAsc ? 1 : -1;
sortcol = args.sortCol.field;
if (isIEPreVer9()) {
// using temporary Object.prototype.toString override
// more limited and does lexicographic sort only by default, but can be much faster
var percentCompleteValueFn = function () {
var val = this["percentComplete"];
if (val < 10) {
return "00" + val;
} else if (val < 100) {
return "0" + val;
} else {
return val;
}
};
// use numeric sort of % and lexicographic for everything else
dataView.fastSort((sortcol == "percentComplete") ? percentCompleteValueFn : sortcol, args.sortAsc);
} else {
// using native sort with comparer
// preferred method but can be very slow in IE with huge datasets
dataView.sort(comparer, args.sortAsc);
}
});
I need to sort data consisting of numbers and letters, this has been working very well for me.
function comparer(a, b) {
var collator = new Intl.Collator(undefined, {
numeric: true,
sensitivity: "base",
});
var x = a[sortcol];
var y = b[sortcol];
return collator.compare(x, y);
}
// add event listener to sort the grid
grid.onSort.subscribe(function (e, args) {
dataView.sort(comparer, args.sortAsc);
});

Check for continuous order in array in javascript

var userInput = prompt('enter number here');
var number = new Array(userInput.toString().split(''));
if (number ????){ //checks if the number is in a continuous stream
alert(correct);
}
else{
alert(invalid);
}
In Javascript, what can I do at "????" to check if it is in a continuous order/stream? Also how can I do this so that it only checks for this order/stream after a specific index in the array? Meaning the user enters say "12345678901234" which would pop up correct, but "12347678901234" would pop up invalid?(note there are two 7's) For the second part "3312345678901234" would pop up correct, how can this be implemented?
You can make a function that checks any string for a stream of continuous/increasing alpha-numeric characters starting at a given index like this:
function checkContinuous(str, startIndex) {
startindex = startIndex || 0;
if (str.length <= startIndex) {
return false;
}
var last = str.charCodeAt(startIndex);
for (var i = startIndex + 1; i < str.length; i++) {
++last;
if (str.charCodeAt(i) !== last) {
return false;
}
}
return true;
}
If it's numbers only and wrapping from 9 back to 0 is considered continuous, then it's a little more complicated like this:
function checkContinuous(str, startIndex) {
// make sure startIndex is set to zero if not passed in
startIndex = startIndex || 0;
// skip chars before startIndex
str = str.substr(startIndex);
// string must be at least 2 chars long and must be all numbers
if (str.length < 2 || !/^\d+$/.test(str)) {
return false;
}
// get first char code in string
var last = str.charCodeAt(0);
// for the rest of the string, compare to last code
for (var i = 1; i < str.length; i++) {
// increment last charCode so we can compare to sequence
if (last === 57) {
// if 9, wrap back to 0
last = 48;
} else {
// else just increment
++last;
}
// if we find one char out of sequence, then it's not continuous so return false
if (str.charCodeAt(i) !== last) {
return false;
}
}
// everything was continuous
return true;
}
Working demo: http://jsfiddle.net/jfriend00/rHH4B/
No need for arrays, just back though the string one character at a time.
When you hit a 0, substitute 10, and continue until the number
is not one more than the previous one.
function continuousFromChar(str, start){
start= start || 0;
var i= 0, L= str.length, prev;
while(L){
c= +(str.charAt(-- L)) || 10; // use 10 for 0
prev=+(str.charAt(L- 1));
if(c-prev !== 1) break;
}
return start>=L;
}
var s= "3312345678901234";
continuousFromChar(s,2)
/* returned value: (Boolean)
true
*/
This will do the checking in real-time entry, but a similar principle could be used to check an entry on a button submit or similar. I was not 100% sure as to which way you wanted it, so I went for the live method.
HTML
<input id="stream" type="text" />
Javascript
window.addEventListener("load", function () {
document.getElementById("stream").addEventListener("keyup", function (evt) {
var target = evt.target;
var value = target.value;
var prev;
var last;
var expect;
target.value = value.replace(/[^\d]/, "");
if (value.length > 1) {
prev = parseInt(value.slice(-2, -1), 10);
last = parseInt(value.slice(-1), 10);
expect = prev + 1;
if (expect > 9) {
expect = 0;
}
if (last !== expect) {
target.value = value.slice(0, value.length - 1);
}
}
}, false);
});
On jsfiddle
By changing the value here
if (value.length > 1) {
You can change where the checking starts.
Update: Ok, so it is function that you want, and you insist that it splits the string into an array. Then using the above as a reference, you could convert it to something like this.
Javascript
window.addEventListener("load", function () {
var testStrings = [
"0123456789012",
"0123456789",
"0123455555",
"555012345678901234",
"0123455555"];
function test(string, offset) {
if (typeof string !== "string" || /[^\d]/.test(string)) {
return false;
}
var array = string.split("");
var prev;
var last;
var expect;
return !array.some(function (digit, index) {
if (index >= offset) {
prev = parseInt(array[index - 1], 10);
last = parseInt(digit, 10);
expect = prev + 1;
if (expect > 9) {
expect = 0;
}
if (last !== expect) {
return true;
}
}
return false;
});
}
testStrings.forEach(function (string) {
console.log(string, test(string, 1));
});
});
On jsfiddle
As your question does not fully specify all possibilities, the above will return true for an empty string (""), of course you can simply add a check at the very beginning for that.
I also do not perform any checking for a valid number for your offset, but again this is something simple that you can add.
Of course these are just one (two) of many possible solutions, but hopefully it will set your mind in the right direction of thought.
There are some good answers here, but I would like to show a slight variation. I think it is important to showcase some different aspects of JavaScript and separating interests in code.
Functions as first class objects are cool - the exact rules for "continuous" can be changed with only changing the predicate function. Perhaps we should allow skipping numbers? No problem. Perhaps we allow hex digits? No problem. Just change the appropriate follows function for the specific rules.
This can be implemented generically because strings support indexing. This will work just as well over other array-like objects with an appropriate follows function. Note that there are no string-specific functions used in the continuous function.
Code also on jsfiddle:
// returns true only iff b "follows" a; this can be changed
function follows_1Through9WithWrappingTo0(b,a) {
if (b === "1" && a === undefined) {
// start of sequence
return true;
} else if (b === "0" && a === "9") {
// wrap
return true;
} else {
// or whatever
return (+b) === (+a) + 1;
}
}
function continuous(seq, accordingTo, from) {
// strings can be treated like arrays; this code really doesn't care
// and could work with arbitrary array-like objects
var i = from || 0;
if ((seq.length - i) < 1) {
return true;
}
var a = undefined;
var b = undefined;
for (; i < seq.length; i++) {
b = seq[i];
if (!accordingTo(b, a)) {
return false; // not continuous
}
a = b;
}
return true;
}
function assert(label, expr, value) {
if (!(expr === value)) {
alert("FAILED: " + label);
}
}
var follows = follows_1Through9WithWrappingTo0;
assert("empty1", continuous("", follows), true);
assert("empty2", continuous("foobar", follows, 6), true);
assert("skip", continuous("331234", follows, 2), true);
assert("good 1", continuous("123456789", follows), true);
assert("good 2", continuous("12345678901234", follows), true);
assert("bad seq 1", continuous("12347678901234", follows), false);
assert("bad seq 2", continuous("10", follows), false);
// here a different predicate ensures all the elements are the same
var areAllSame = function (b, a) {
return a === undefined || a === b;
};
assert("same", continuous("aaaaa", areAllSame), true);
Note that the skipping could also be extracted out of the continuous function: in a language with better "functional" collection support, such as C#, this is exactly what I'd do first.

Is there a way to check if several vars are all equal to each other in javascript?

I have jQuery included so if it helps to use it, it's available.
First the simple question:
Is there a way to check if several vars are all equal to each other?
I can use the transitive relation logic and do
if ((a == b) && (b == c)) && (c == d)) ... {
to avoid checking every variable against EACH other, but I think there should be a fancier way to do this.
If you can answer this first part only, it would be much appreciated.
Now, the tricky part...
I have a variable amount of variables (between 1 and 5)
I know that their value can be any of 200 possible values from a DDBB.
What would be the best way to know how many instances of each value I have within those variables?
For example...
If I have...
var1 = VALUE_A;
var2 = VALUE_A;
var3 = VALUE_B;
var4 = VALUE_Z;
var5 = VALUE_Z;
... i want to get something like:
result["VALUE_A"] => 2
result["VALUE_B"] => 1
result["VALUE_Z"] => 2
///////////////////////////
OR if i have...
var1 = VALUE_A;
var2 = VALUE_C;
var3 = VALUE_B;
... get:
result["VALUE_A"] => 1
result["VALUE_C"] => 1
result["VALUE_B"] => 1
///////////////////////////
OR if i have...
var1 = VALUE_A;
var2 = VALUE_A;
var3 = VALUE_A;
var4 = VALUE_C;
var5 = VALUE_C;
... get:
result["VALUE_A"] => 3
result["VALUE_C"] => 2
///////////////////////////
OR if i have...
var1 = VALUE_A;
var2 = VALUE_A;
var3 = VALUE_A;
... get:
result["VALUE_A"] => 3
Hope I was clear. Examples were the only way I could think of explaining clearly.
If this is too complex for Javascript or processing so many possible values up to times 5 can make the browser slow I can do it in PHP and get the result via AJAX but I'd rather not.
Would something like this do?
function countOccurrences(arr) {
var result = {};
$.each(arr, function(index, value) {
if (!result[value])
result[value] = 1;
else
result[value]++;
});
return result;
}
This function accepts an array of the values, and returns an object whose keys are the elements and values are the number of occurrences of each.
For your first question, I don't think there's any special way of doing that.
For the 2nd: I would suggest storing those variables in an array. So your code becomes :
var myVars = [];
myVars[0] = VALUE_A;
myVars[1] = VALUE_A;
myVars[2] = VALUE_B;
myVars[3] = VALUE_Z;
myVars[4] = VALUE_Z;
Then you can just simply loop through the array and count the occurrences of each value.
The short answer is no, that is not possible. JavaScript allows for local variable definitions which can't be lifted from the environment.
The long answer is more nuanced. Variables which are declared without var or variables which are declared right on the window often are accessible, but it is a headache to do that. And you can often get a variable's value through eval, but that still does not give access to the variable's name (which is what you need for all of the above).
If you have a series of known values, then you can loop through the variables:
var tests = [
VALUE_A,
VALUE_B,
VALUE_A,
VALUE_C
]
function areAllEqual( arr )
{
for( var i = 0; i < arr.length - 1; i++ )
{
if( arr[ i ] != arr[ i + 1 ] ) return false;
}
return true;
}
console.log( areAllEqual( tests ) ) // false;
console.log( areAllEqual( [1,1,1] ) ) // true;
function getOccurances(arr) {
var result = {};
for( var i = 0; i < arr.length; i++ )
{
if( isNaN( result[ arr[ i ] ] ) ) result[ arr[ i ] ] = 1;
else result[ arr[ i ] ]++;
}
return result;
}
// this is not guaranteed to be in any order.
console.log( getOccurances( tests ) ) // {VALUE_A:2, VALUE_B:1, VALUE_C:1};
Answering the first question.
This function might help if there are a lot of variables to compare.
function allEq(arr)
{
var next;
var curr = arr.pop();
while (arr.length)
{
next = arr.pop();
if (curr != next)
return false;
curr = next;
}
return true;
}
var a = 1, b = 1, c = 1, d = 1;
var myArr = [a, b, c, d];
if (allEq(myArr)) ... {
I think you need to create your own object. The object is basically a wrapper around an array of key/value pairs. Then you need a couple of methods for .isTrue() or whatever.
You said you wanted something fancier....
So why not add to the Array object your own methods and properties to get the job done.... Hopefully, it's clear enough.
KeyValuePair.prototype.value = null;
KeyValuePair.prototype.key = null;
function KeyValuePair(key, value) {
this.key = key;
this.value = value;
this.Equals = Equals;
function Equals(o) {
if (this.value == o.value)
return true;
else
return false;
}
}
Array.prototype.ValuesAreEqual = ValuesAreEqual;
Array.prototype.GetValues = GetValues;
function ValuesAreEqual() {
this.sort();
for (var i = 0; i <= this.length - 1; i++) {
var last = this.pop();
var first = this.shift();
if (first) {
return first.Equals(last);
}
}
}
function GetValues(value) {
var arr = new Array();
if (this.length > 0) {
for (var i = 0; i <= this.length - 1; i++) {
if (this[i].value) {
if (this[i].value == value) {
arr.push(this[i].value);
}
}
}
}
return arr;
}
//code below would demonstrate the functionality of the above.
var x = new Array();
x.push(new KeyValuePair("A","Hello"));
x.push(new KeyValuePair("B","Hello"));
x.push(new KeyValuePair("C","Hello"));
var y = x.GetValues("Hello");
document.writeln(y.length);
document.writeln('\r\n');
document.writeln(x.ValuesAreEqual());

What is the fastest way to check whether a specific UserID exists in the array using Jquery or Javascript

I have an array of objects gAllMedicalFilesClaimantsArray with 2 properties (UserID & UserInfo)
For example:
gAllMedicalFilesClaimantsArray[0].UserID = "111";
gAllMedicalFilesClaimantsArray[0].UserInfo = "AAA-111";
gAllMedicalFilesClaimantsArray[1].UserID = "222";
gAllMedicalFilesClaimantsArray[1].UserInfo = "BDD-478333";
What is the fastest way to check whether a specific UserID exists in the array using Jquery or Javascript because gAllMedicalFilesClaimantsArray has got 8000 records?
Thanks
var match = '222';
var matches = $.grep(myArray, function(el, index) {
return (el.UserID === match);
});
You can fasten the search process by using Binary Search algorithm if the array is sorted (e.g with respect to UserId).
function binarySearch(array, userid) {
var low = 0, high = array.length - 1,
i, comparison;
while (low <= high) {
i = parseInt((low + high) / 2, 10);
if (array[i].UserId < userid) { low = i + 1; continue; };
if (array[i].UserId > userid) { high = i - 1; continue; };
return array[i];
}
return null;
};
You can find the user of which ID is 12 by using the function:
var result = binarySearch(gAllMedicalFilesClaimantsArray, 12);
Something like this, I believe:
function exists(uid) {
var k = gAllMedicalFilesClaimantsArray.length;
uid = uid.toString(); // ensure the arg is a str (this can be omitted)
while (k--) {
if (gAllMedicalFilesClaimantsArray[k].UserID === uid) {
return true;
}
}
return false;
}
Is the array sorted by the UserID? If so, it can be improved either further by using a binary search; that would change this from O(n) to O(log n). Your example suggests it is. I found a good implementation of a binary search in JavaScript on the web, here. Here is the code if the site ever dies:
function binarySearch(items, value){
var startIndex = 0,
stopIndex = items.length - 1,
middle = Math.floor((stopIndex + startIndex)/2);
while(items[middle] != value && startIndex < stopIndex){
//adjust search area
if (value < items[middle]){
stopIndex = middle - 1;
} else if (value > items[middle]){
startIndex = middle + 1;
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex)/2);
}
//make sure it's the right value
return (items[middle] != value) ? -1 : middle;
}
ExistsInArray(value, array){
for(var item in array){
if(item.UserId == value){
return true;
}
}
return false;
}
You can either prototype Array object, like this:
Array.prototype.exists = function(value, prop){
var i = null;
for (i in this)
if (this[i][prop] && this[i][prop] == value)
return true;
return false;
}
gAllMedicalFilesClaimantsArray.exists('222', 'UserID');

Categories