Re: Array manipulation question
- From: timothytoe <timothytoe@xxxxxxxxx>
- Date: Fri, 30 May 2008 17:57:47 -0700 (PDT)
On May 30, 5:50 pm, timothytoe <timothy...@xxxxxxxxx> wrote:
On May 30, 6:03 am, DL <tatata9...@xxxxxxxxx> wrote:
say, we have the following:
// declare an array
myArray = []; // short hand? same as myArray = new Array ?
// populate it
myArray[0] = 0;
myArray[1] = 0;
myArray[2] = 1;
myArray[3] = 0;
// now problem to solve
// fact: the above array has 4 sets of data, namely 3 zeros and 1 of
value one.
// say, the business rule is, if all set of data are of same value ( 0
|| 1), then do nothing
else alert ('hey dark sheep found').
I understand Array has a bunch of methods, but not sure which one is a
good one to solve the above problem.
Thanks.
Here's an interesting way. It occurred to me that the JavaScript
"some" method could be used with a bit of work...
function monoArray(arr) {
function isEqToFirst(element,index,array) {
return (element!==array[0]);
}
if (arr && arr.length>0) {
return !(arr.some(isEqToFirst));
}
}
var passed = monoArray([2,5,8,1,4]);
alert(passed); //false
passed = monoArray([12, 12, 12, 12, 12]);
alert(passed); //true
passed=monoArray([5]);
alert(passed); //true
passed=monoArray([]);
alert(passed); //undefined
passed=monoArray();
alert(passed); //undefined
passed=monoArray(5);
alert(passed); //undefined
This only works for JavaScript interpreters which have the "some"
method. See "compatibility" here for the code to add if you're afraid
of running into older, less capable ECMAScript implementations.
http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Gl...
Sent too early. A more compact version of the same thing:
function monoArray(arr) {
if (arr && arr.length>0) {
return !arr.some(function(element,index,array) {
return element!==array[0];
});
}
}
.
- References:
- Array manipulation question
- From: DL
- Re: Array manipulation question
- From: timothytoe
- Array manipulation question
- Prev by Date: Re: Array manipulation question
- Next by Date: Re: Array manipulation question
- Previous by thread: Re: Array manipulation question
- Next by thread: Re: Array manipulation question
- Index(es):