3

I have an array in JavaScript like this

var arr = [];
arr['5u'] = 250;
arr['1u'] = 120;
arr['7u'] = 670;
arr['2u'] = 210; //<-----
arr['9u'] = 850; //<-----
arr['8u'] = 129; //<-----
arr['3u'] = 382;
arr['6u'] = 391;
arr['4u'] = 432;

I want to get only 3 elements starting from index of 3 to 5 in above array. How can I get so? the result should be something like this.

[210,850,129];

I tried accessing it as arr[3] and off-course as it should it is showing undefined. Now how can I get so?

I want to access values with loop like this

for(var i=3; i<6; i++)
{
    console.log(arr[i]);
}
13
  • 3
    You are just adding property the the array object but not putting elements in the array. When you need a hash structure, use object {} instead of []. Commented Mar 11, 2014 at 5:39
  • Well I thought so but then I would not be able to sort it Commented Mar 11, 2014 at 5:39
  • You can't sort it too. arr.sort(function(a, b) {return b - a}); will just return an empty array. Commented Mar 11, 2014 at 5:41
  • 3
    You can't rely on sorting by object keys. Commented Mar 11, 2014 at 5:43
  • 1
    Then better you suggest the one that is good Commented Mar 11, 2014 at 6:03

8 Answers 8

2

I would suggest you to use this technique

arr[0] = [250, '5u'];
arr[1] = [120, '1u'];
arr[2] = [670, '7u'];
arr[3] = [210, '2u'];
arr[4] = [850, '9u'];
arr[5] = [129, '8u'];
arr[6] = [391, '3u'];
arr[7] = [432, '6u'];

now you can sort like this

arr.sort(function(a, b) {return b[0] - a[0]});

and access any element like this

console.log(arr[3][0]);
console.log(arr[4][0]);
console.log(arr[5][0]);
Sign up to request clarification or add additional context in comments.

5 Comments

This looks promising. Let me try it please
@CodeDevil Out of curiosity, what's different about this answer compared to mine?
@Jack in first I just liked this answer and it was just exactly what I wanted but when you asked about the difference between yours and this. I thought that this is simple and working great but then I made few benchmarks and this answer is much faster than yours. You can try it yourself with loop of 1000000. This answer is taking approx. 4 seconds to sort array and yours is taking about 10 seconds.
@CodeDevil I don't see how that's possible by just having the values reversed inside each element? Do you have a benchmark on jsperf.com?
Hold on I just removed. Let me make again. I really appreciate what you suggest. Wait please
1

Since you have provided keys for the array, you need to access using arr['2u'], arr['9u'] and arr['8u']. You can't access using arr[3] as it is not stored with those indices.

3 Comments

It is not sure what would be index since array would be sorted. Means I am not sure what will be either 9u, 8u or so. I just know that I want to get so and so index numbered element
What does means that you know what you want to get?... like from fourth element to the sixth?, i think you should explain better, since anirudh answer is just what you asked, try reformulating
Are you sorting based on the indices or the values of the array?
1

To be absolutely safe, you're going to need parallel data structures. What you're describing is a map not an array. The problem is a map is unordered so you can't rely on the order of the elements you put in it. You're going to need an accompanying array to keep track of the order. See this: Ordered hash in JavaScript

Comments

1

I would populate the array in this manner:

var arr = [], 
map = {},
append = function(key, value) {
    return arr[map[key] = arr.length] = [key, value];
}

append('5u', 250);
append('1u', 120);
append('7u', 670);
append('2u', 210); //<-----
append('9u', 850); //<-----
append('8u', 129); //<-----
append('3u', 382);
append('6u', 391);
append('4u', 432);

The map structure allows you to find an element by its identifier.

In this way, you can use arr.slice():

arr.slice(3, 6); // [['2u', 210], ['9u', 850], ['8u', 129]]

Sorting this will maintain the key - value pairs as well:

arr.sort(function(a, b) {
    return a[1] - b[1]; // or reversed, whatever
});

Note that after a sort you will have to rebuild the map; that's if you would actually that structure.

Comments

1

YOU CAN CREATE YOUR OWN PROTOTYPE FUNCTION FOR ARRAY LIKE THIS BELOW,

Array.prototype.selectIndex = function (n) {
          var count = 0;
          for (var i in arr) {
              if (count == n) val = arr[i];
              count++;
          }
          console.log(val);
      };

and you can simply enter the index number like this below,

arr.selectIndex(3);
arr.selectIndex(4);
arr.selectIndex(5);

SEE THIS DEMO

1 Comment

Properties in an object don't necessarily have a fixed ordering.
1
You can use this way also

var arr = {};    
arr[0] = {'key':'5u','val':250};
arr[1] = {'key':'1u','val':120};
arr[2] = {'key':'7u','val':670};
arr[3] ={'key':'2u','val':210}; //<-----
arr[4] ={'key':'9u','val':850}; //<-----
arr[5] ={'key':'8u','val':129}; //<-----
arr[6] ={'key':'3u','val':382};
arr[7] = {'key':'6u','val':391};
arr[8] ={'key':'4u','val':432};
console.log(arr[3]['val']);
console.log(arr[4]['val']);
console.log(arr[5]['val']);

1 Comment

If you're using objects it would be better to use {key: '5u', value: 250}.
0

Try this code

 var arr = [], arr2 = [];
    arr['5u'] = 250;
    arr['1u'] = 120;
    arr['7u'] = 670;
    arr['2u'] = 210; //<-----
    arr['9u'] = 850; //<-----
    arr['8u'] = 129; //<-----
    arr['3u'] = 382;
    arr['6u'] = 391;
    arr['4u'] = 432;
    var count = 0;
    for(var i in arr){

        if(count == 3 || count == 4 || count == 5)
            arr2.push(arr[i]);
     count++;
    }

    console.log(arr2)

DEMO

2 Comments

Your answer is good but isn't there any way to access it directly with index because this way we have to loop from start everytime it is called. I will not be that good if the array has about 100000 values to handle and accessing only last 3 elements
@Girish Lol, almost same approach that mine. What if you want the index you can store the i value in the second array, then you can use the keys to access the main array, but i see no point, at least in what you showed us.
0
var len = arr.length;
var data=new array();
var i=0;
while (len--){
    if(i==3) {
        data[i-3]=arr[i];
    }    
    i++;
    if(i==5){
        break;
    }
}

now, your data array will contain desired values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.