...

View Full Version : get max,min y value for each x in javascript 2d integer array



oah1837
05-19-2012, 02:00 PM
Hi all,

this is my first post to this great useful forum.

I have a javascript 2d array [x,y] that contains integer values like this:

[0,0], [0,1], [0,2], [0,3],
[1,0], [1,1], [1,2],
[2,0], [2,1], [2,2],
[0,-1], [0,-2], [0,-3],
[1,-1], [1,-2],
[2,-3]

my question is how to get the max,min y value for each x.
for the sample above it should give me another array with the following results
[0,3],[0,-3],[1,2],[1,-2],[2,2],[2,-3]

your help is highly appreciated

Regards
Omran

chump2877
05-19-2012, 03:22 PM
Run that in Firefox because toSource() is only supported in Gecko browsers:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
<title>TITLE</title>
</head>
<body>

<script type="text/javascript">

var arr = [[0,0], [0,1], [0,2], [0,3], [1,0], [1,1], [1,2], [2,0], [2,1], [2,2], [0,-1], [0,-2], [0,-3], [1,-1], [1,-2], [2,-3]];
var ordered = [];
for (var i=0; i<arr.length; i++)
{
ordered[arr[i][0]] = (ordered[arr[i][0]] == undefined) ? [] : ordered[arr[i][0]];
ordered[arr[i][0]].push(arr[i]);
}

var outputArr = [];
var count = -1;
for (var i=0; i<ordered.length; i++)
{
var lowHighFinal = [];
for (var j=0; j<ordered[i].length; j++)
{
var yVal = ordered[i][j][1];
if (j > 0)
{
lowHighFinal[0] = (compareXY(yVal, lowHighFinal[0]) == -1) ? yVal : lowHighFinal[0];
lowHighFinal[1] = (compareXY(yVal, lowHighFinal[1]) == 1) ? yVal : lowHighFinal[1];
}
else
{
lowHighFinal = [yVal, yVal];
}
}
outputArr[++count] = [i, lowHighFinal[1]];
outputArr[++count] = [i, lowHighFinal[0]];
}

alert(outputArr.toSource());

function compareXY(a, b)
{
return (a >= b) ? 1 : -1;
}

</script>

</body>
</html>

The code can probably be refactored a little bit, but this gives you an idea of how to do what you want.

oah1837
05-19-2012, 04:54 PM
thank u chump2877 for your help

the code works perfectly

Regards
Omran



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum