javascript - Get minimum and maximum of object property names that are integers - Stack Overflow

UPDATED(formulated the problem wrong, see note below)I have an object that has a set of properties th

UPDATED (formulated the problem wrong, see note below)

I have an object that has a set of properties that are named with numbers as shown in the example. The 'numbered names' are not necessarily consecutive, nor do I know where they start or end. I do know that other properties will not be named with numbers.
I know that myObject["propName"] is the same as myObject.propName, but I deliberately write it in the first way because myObject.0 looks weird and doesn't get recognized by all editors.

How do I get the min- and maximum array index?

So in a situation like this

myObject["0"] = undefined
myObject["1"] = {}
myObject["2"] = undefined
myObject["3"] = {}
myObject["4"] = {}
myObject["5"] = undefined
myObject["someOtherProperty"] = {}

would give me this

minIndex(myObject) == 1
maxIndex(myObject) == 4

To all the answers before this edit
Thanks for your replies. I shouldn't have posted this question in a hurry and should have re-read it before mitting. It was late and I was in a hurry. My apologies.
By actually seeing my wrong statement (using an array instead of an object) I think that, based on answers for my reformulated problem, I might need to rewrite my code to use an array instead of an object. The reason I'm using an object rather then an array is material for another question.

Efforts so far
I have tried finding a way of converting the property names to an array and then looping through them, but that has proven cludgy. I'm kind of looking for a less error-prone and elegant way.

UPDATED (formulated the problem wrong, see note below)

I have an object that has a set of properties that are named with numbers as shown in the example. The 'numbered names' are not necessarily consecutive, nor do I know where they start or end. I do know that other properties will not be named with numbers.
I know that myObject["propName"] is the same as myObject.propName, but I deliberately write it in the first way because myObject.0 looks weird and doesn't get recognized by all editors.

How do I get the min- and maximum array index?

So in a situation like this

myObject["0"] = undefined
myObject["1"] = {}
myObject["2"] = undefined
myObject["3"] = {}
myObject["4"] = {}
myObject["5"] = undefined
myObject["someOtherProperty"] = {}

would give me this

minIndex(myObject) == 1
maxIndex(myObject) == 4

To all the answers before this edit
Thanks for your replies. I shouldn't have posted this question in a hurry and should have re-read it before mitting. It was late and I was in a hurry. My apologies.
By actually seeing my wrong statement (using an array instead of an object) I think that, based on answers for my reformulated problem, I might need to rewrite my code to use an array instead of an object. The reason I'm using an object rather then an array is material for another question.

Efforts so far
I have tried finding a way of converting the property names to an array and then looping through them, but that has proven cludgy. I'm kind of looking for a less error-prone and elegant way.

Share Improve this question edited Aug 14, 2012 at 12:11 Boris Callens asked Aug 9, 2012 at 20:11 Boris CallensBoris Callens 93.5k86 gold badges210 silver badges308 bronze badges 6
  • 2 By the way... you can remove items from an array without the ugly holes with array.splice(). Maybe this eradicates the question in the first place. – Kai Mattern Commented Aug 9, 2012 at 20:18
  • 4 I would close the question. These types of questions, besides not showing any research effort, always end up in a Crazy Coding Contest (C3). There is not enough time on Earth to correct everything in all the answers, and if I downvote most of them for various reasons, angry townspeople might attack my home. – kapa Commented Aug 9, 2012 at 20:29
  • 1 Wow, haven't looked this for a workday and then this. Quite shocked. Yes, I'm quite new to real javascript. Furthermore I think that, in my effort to give only the core problem, I might have boiled the question down incorrect and posed the problem wrong. I'm going to try and review the entire thing. But really: ouch – Boris Callens Commented Aug 10, 2012 at 15:56
  • @Esailija, you are right to question this. Reformulated question, added response to you request in OP – Boris Callens Commented Aug 10, 2012 at 16:11
  • 1 @Boris Callens I updated my answer. Let me know if this works given the "updated scenario" :) – Nick Commented Aug 10, 2012 at 19:31
 |  Show 1 more ment

7 Answers 7

Reset to default 10

Edit: Aha! Now the problem bees more interesting.

Solution 1: Let's solve this in one shot, shall we? For max:

function maxIndex(obj){
    var max = -1;
    for(var i in myObject){
        var val = parseInt(i);
        if(isFinite(val)){
            if(typeof obj[val] !== 'undefined' && val > max){
                max = val;
            }
        }
    }
    return max;
}

I think you can convert this to min on your own ;)

Solution 2: Here I'll your object back into what we originally thought it was, in case you really loved one of the other solutions. Then the rest of the answer applies.

function convertObject(obj){
    var output = [];
    for(var i in myObject){
        var val = parseInt(i);
        if(isFinite(val)){         
            output[val] = obj[i]; //Gotta love JS
        }
    }
    return output;
}

Continue as planned!


To find the smallest, begin at the bottom and work your way up until you find it.

function minIndex(myArray){
    for(var i = 0; i < myArray.length; i++){
        if(typeof myArray[i] !== 'undefined')
            return i;
    }
}

To get the biggest, start at the top.

function maxIndex(myArray){
    for(var i = myArray.length - 1; i >= 0; i--){
        if(typeof myArray[i] !== 'undefined')
            return i;
    }
}

Both are worst case O(n). You can't really do better because the whole array could be empty, and you'd have to check every element to be positive.

Edit: As is mentioned, you can also check if something is not undefined by simply writing if(myArray[i]). Whatever suits your fancy.

var myObject = {};
myObject["0"] = undefined;
myObject["1"] = {};
myObject["2"] = undefined;
myObject["3"] = {};
myObject["4"] = {};
myObject["5"] = undefined;
myObject["someOtherProperty"] = {};

var keys = Object.keys(myObject).map(Number).filter(function(a){
    return isFinite(a) && myObject[a];
});

var min = Math.min.apply(Math, keys);
var max = Math.max.apply(Math, keys);

console.log(min, max); //Logs 1 and 4

Documentation and patibility information for all:

https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/Object/keys
https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

Try looping through the array until you find the 1st non-undefined element.

function minIndex(arr){
    for(var i = 0, len = arr.length; i < len; i++){
        if(arr[i] !== undefined){
            return i;
        }
    }
}

For max index, do the same thing, except in reverse.

function maxIndex(arr){
    for(var i = arr.length-1, len = 0; i >= len; i--){
        if(arr[i] !== undefined){
            return i;
        }
    }
}

Min:

for(var i = 0; i < myArray.length; i++) {
    if(myArray[i] != undefined) {
        return i;
    }
}

Max:

for(var i = myArray.length-1; i >= 0; i--) {
    if(myArray[i] != undefined) {
        return i;
    }
}

try something like this:

function minIndex(var array){
   for(var i = 0; i < array.length; i++)
   {
      if(typeof array[i] != "undefined")
      return i;
   }
   return null;
}

function maxIndex(var array){
   var returnIndex = -1;
   for(var i = 0; i < array.length; i++)
   {
      if(typeof array[i] != "undefined")
      returnIndex = i;
   }
   if(returnIndex !== -1) return returnIndex;
   else return null;
}

this takes advantage of the fact that for..in only iterates over defined elements, and uses the index:

function minIndex(arr){ for(el in arr){return el} }

function maxIndex(arr){var v; for(el in arr){v = el}; return v }

CAVEATS: The second function is not very efficient though, since it loops through the entire array. This wont work if you are EXPLICITLY setting the undefined indexes.

var max=0;
var min=myArray.length;
for (var i in myArray)
    if (myArray[i]!==undefined)
    {
        max=Math.max(i, max);
        min=Math.min(i, min);
    }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745049114a4608276.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信