This is wrong:
if(coin.value > highest){
highest = coin; //
}
Possible code for searching the highest coin value and the coin with the highest value:
var coins = [{value:1, pos:{x:1, y:1}},
{value:2, pos:{x:2, y:2}},
{value:3, pos:{x:3, y:3}},
{value:4, pos:{x:4, y:4}},
{value:5, pos:{x:5, y:5}}
];
function getHighestCoinValue(coins){
var highestCoinValue = 0;
for(var i = 0; i < coins.length; i ++){
var coin = coins[i];
if(coin.value > highestCoinValue){
highestCoinValue = coin.value;
}
}
return highestCoinValue;
}
function geCoinWithHighestValue(coins){
var highestCoinValue = 0;
var coinWithHighestValue = null;
for(var i = 0; i < coins.length; i ++){
var coin = coins[i];
if(coin.value > highestCoinValue){
highestCoinValue = coin.value;
coinWithHighestValue = coin
}
}
return coinWithHighestValue;
}
console.log(getHighestCoinValue(coins));
console.log(geCoinWithHighestValue(coins));
use pythontutor to paste the code and see it working step by step
your original function creates something that doesn’t work in codecombat and that I cannot exactly understand what is going on …
function getCoin(coins){
var highest = 0;
for(var i = 0; i < coins.length; i ++){
var coin = coins[i];
if(coin.value > highest){
highest = coin; // assigning an object to a number var
// and then comparing the object to a number var
}
}
return highest ;
}
console.log(getCoin(coins));
/////////////////////////////////// Edit //////////////////////////////////////////////////////////////
Your idea can work if you create an object with a value field:
// Test data
var coins = [{value:1, pos : {x: 1, y:1}},
{value:2, pos : {x: 2, y:2}},
{value:5, pos : {x: 5, y:5}},
{value:3, pos : {x: 3, y:3}},
{value:4, pos : {x: 4, y:4}}
];
// code
function getCoin(coins){
var highest = {};
highest.value = 0;
for(var i = 0; i < coins.length; i ++){
var coin = coins[i];
if(coin.value > highest.value){
highest = coin;
}
}
return highest ;
}
var highestCoin = getCoin(coins);
console.log(highestCoin);
Visualization: