javascript equivalent to php max for arrays - php

I have a function in php that selects the array with that contains the most elements.
$firstArray = array('firstArray','blah','blah','blah');
$secondArray = array('secondArray','blah','blah');
$thirdArray = array('thirdArray','blah','blah','blah','blah');
then I get the name of the variable with the highest length like this:
$highest = max($firstArray, $secondArray, $thirdArray)[0];
but I am developing an application and I want to avoid using php and I have tried javascript's Math.max() to achieve the same results but it doesn't work the same way unless I do
Math.max(firstArray.length, secondArray.length, thirdArray.length)
But this is useless since I need to know the name of the array that contains the most elements. Is there any other way to achieve this?

This function takes as input an array of arrays, and returns the largest one.
function largestArray(arrays){
var largest;
for(var i = 0; i < arrays.length; i++){
if(!largest || arrays[i].length > largest.length){
largest = arrays[i];
}
}
return largest;
}
We can test it out with your example:
firstArray = ['firstArray','blah','blah','blah'];
secondArray = ['secondArray','blah','blah'];
thirdArray = ['thirdArray','blah','blah','blah','blah'];
// should print the third array
console.log(largestArray([firstArray, secondArray, thirdArray]));

The following url has a max() equivalent. It supports more then just numbers just like in php:
js max equivalent of php

If you feel ok with including 3rd-party libs, maybe http://underscorejs.org/#max does what you want:
var aList = [firstArray, secondArray, thirdArray];
_.max(aList, function(each) { return each.length; });

Related

What is the fastest way to pass database cell values to many different PHP variables?

I have an Oracle database which serves as an array of ~70 values. I am trying to find the most efficient code to pass each cell value to a variable, preferebly coded in PHP.
Example:
Cell1 Cell2 Cell3 Cell4 ... Cell70
Pass each cell 1-70 to a variable named after that cell:
($CELL1, $CELL2, $CELL3, $CELL4 ... $CELL70)
I can think of no practical reason to use multiple variables over an array, but you could in theory use variable variables:
for ($i = 0; $i < count($arr); $i++) {
${"Cell" + $i} = $arr[$i];
}
Instead it would be much simpler to just use $arr["Cell1"] in spots where you may want to use $Cell1.
It'd be FAR simpler to just use an array:
$arr = oci_fetch_array(...);
so you don't pollute the namespace with a bunch of (mostly) useless variables.
If you INSIST on going this route, then you could try:
list($cell1, $cell2, $cell3, ...., $cellWayTooManyCells) = oci_fetch_array(...);
Or
$arr = oci_fetch_assoc(...);
extract($arr);

Find index of value in associative array in php?

If you have any array $p that you populated in a loop like so:
$p[] = array( "id"=>$id, "Name"=>$name);
What's the fastest way to search for John in the Name key, and if found, return the $p index? Is there a way other than looping through $p?
I have up to 5000 names to find in $p, and $p can also potentially contain 5000 rows. Currently I loop through $p looking for each name, and if found, parse it (and add it to another array), splice the row out of $p, and break 1, ready to start searching for the next of the 5000 names.
I was wondering if there if a faster way to get the index rather than looping through $p eg an isset type way?
Thanks for taking a look guys.
Okay so as I see this problem, you have unique ids, but the names may not be unique.
You could initialize the array as:
array($id=>$name);
And your searches can be like:
array_search($name,$arr);
This will work very well as native method of finding a needle in a haystack will have a better implementation than your own implementation.
e.g.
$id = 2;
$name= 'Sunny';
$arr = array($id=>$name);
echo array_search($name,$arr);
Echoes 2
The major advantage in this method would be code readability.
If you know that you are going to need to perform many of these types of search within the same request then you can create an index array from them. This will loop through the array once per index you need to create.
$piName = array();
foreach ($p as $k=>$v)
{
$piName[$v['Name']] = $k;
}
If you only need to perform one or two searches per page then consider moving the array into an external database, and creating the index there.
$index = 0;
$search_for = 'John';
$result = array_reduce($p, function($r, $v) use (&$index, $search_for) {
if($v['Name'] == $search_for) {
$r[] = $index;
}
++$index;
return $r;
});
$result will contain all the indices of elements in $p where the element with key Name had the value John. (This of course only works for an array that is indexed numerically beginning with 0 and has no “holes” in the index.)
Edit: Possibly even easier to just use array_filter, but that will not return the indices only, but all array element where Name equals John – but indices will be preserved:
$result2 = array_filter($p, function($elem) {
return $elem["Name"] == "John" ? true : false;
});
var_dump($result2);
What suits your needs better, resp. which one is maybe faster, is for you to figure out.

Altering an Array with Array Walk

I have an array that I want to alter. I thought that array_walk would be the way to go but I'm having trouble figuring out how to collect that data from array_walk, deleting the data from the old array, and inserting the new data. How should I go about doing this? Here is the code.
$width_array = array(
"2.5%",
"2.6%",
"2.7%",
"2.8%",
);
function adjust_the_width($value)
{
$value = $value * 2;
}
array_walk($width_array, "adjust_the_width");
$random_width = array_rand($width_array, 10);
You where likely looking for array_map, example below:
<?
$width_array = array(
"2.5%",
"2.6%",
"2.7%",
"2.8%",
);
function adjust_the_width($value) {
return $value * 2;
}
$width_array = array_map("adjust_the_width", $width_array);
$random_width = array_rand($width_array, count($width_array));
var_dump($width_array);
Note: the percentages are dropped from the calculations because PHP interprets the string "2.5%" as a float value when it is multiplied by 2.
Also, array_map supplies each element as the parameter to the function provided and uses it's return value to fill the same place in the new array that array_map builds.
This is also why I assign $width_array = array_map(..., array_map builds a new array, it does not replace the old one by default.
You can also do this if you'd rather not build the intermediate array:
foreach($width_array as &$width) {
$width = $width * 2;
}
var_dump($width_array);
This walks the array and modifies each element as a reference to it's location (that's what &$width means).
Without the '&' this foreach loop will do nothing but chew cpu cycles.

php array count max value

If I have:
$mainarray = some array of things with some repeated values
$array_counted = array_count_values ($mainarray);
How can I find the maximum value in $array_counted?
(This would be the element that appeared most often in $mainarray I think. Its mostly a syntax issue as I am pretty sure I could loop it, but not sure of the syntax to use)
You can find first max value as
$main_array = array(1,2,3,4,5,6,6,6,6,6,6,6);
$max_val = max($main_array);
for find all of max vals
in php < 5.3
function findmax($val)
{
global $max_val;
return $val == $max_val;
}
$max_values_array = array_filter($main_array,'findmax');
in php >= 5.3
$max_values_array = array_filter($main_array,function($val) use ($max_val) { return $val == $max_val; });
echo count($max_values_array);
var_dump($max_values_array);
You could sort the array and take the first, respectively last item out of it, if you don't want to loop.
Since you associate the count with the values with that:
$array_counted = array_count_values ($mainarray);
You only need to sort it afterwards, and return the first key (which is the most occured element):
arsort($array_counted);
print key($array_counted); // returns first key
ok, the guy whos answer I used has deleted his comment so here is how I did it:
I used arsort($array_counted) to sort the array, while keeping index. rsort alone does not work as the result of array_count_values is an associative array. Thank you all.

Passing by reference in AS3

How do I pass values by reference inside a for each construct in AS3? Basically, I want something equivalent to the following code in PHP:
foreach ($array as &$v) {
$v = $v + 1;
}
This would allow me to change all elements of the collection $array through a single loop.
Pointers don't exist in AS3 so you need to use Array.forEach method that executes a function on each item in the array:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html?filter_coldfusion=9&filter_flex=3&filter_flashplayer=10&filter_air=1.5#forEach%28%29
A bit off-topic but more info about values and references in AS3 (for functions)
In ActionScript 3.0, all arguments are passed by reference because all values are stored as objects. However, objects that belong to the primitive data types, which includes Boolean, Number, int, uint, and String, have special operators that make them behave as if they were passed by value.
http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f56.html
You can not do this they way you do it in PHP. The for each loop will yield a reference variable v you can use to get the value, but setting v=v+1 would not change the original array, but erase the reference and set a new value only to v. But you can still modify all array values in one loop:
For a simple Array:
var array1 : Array = [ "one", "two", "three" ];
for (var i : int = 0; i < array1.length; i++)
{
array1[i] = "number " + array1[i];
}
For an associative array (it's actually an Object in Flash), use for...in:
var array2 : Object = { one:"one", two:"two", three:"three" };
for (var s:String in array2) // s is the string value of the array key
{
array2[s] = "number " + array2[s];
}
I think the second one is what you are looking for.
EDIT: weltraumpirat was correct. My original example wasn't modifying the contents of the original array which is probably what the original poster wanted. Here's some updated examples:
Updated example using for each:
for each (var s:String in arr)
{
arr[arr.indexOf(s)] = "<Your value here>";
}
Updated example using a standard for loop:
for (var counter:int = 0; counter < arr.length; counter++)
{
arr[counter] = "<your value here>";
}
Original example [Incorrect]:
for each (var s:String in array)
{
s = <your value here>;
}

Categories