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]);
}
  • 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 `[]`. – xdazz Mar 11 '14 at 05:39
  • Well I thought so but then I would not be able to sort it –  Mar 11 '14 at 05:39
  • You can't sort it too. `arr.sort(function(a, b) {return b - a});` will just return an empty array. – xdazz Mar 11 '14 at 05:41
  • Well if so then what would be the idea to solve it? –  Mar 11 '14 at 05:43
  • 3
    You can't rely on sorting by object keys. – dfsq Mar 11 '14 at 05:43
  • I have to sort by values not by keys –  Mar 11 '14 at 05:44
  • for the time being if we ignore sorting case what would be the rest to do? –  Mar 11 '14 at 05:45
  • So you know what values you need? – dfsq Mar 11 '14 at 05:45
  • I have updated my question, now that should make better sense –  Mar 11 '14 at 05:47
  • 1
    Then better you suggest the one that is good –  Mar 11 '14 at 06:03
  • It is just a simple array which is populated dynamically with keys having string indices –  Mar 11 '14 at 06:04
  • Use "standard" array or it's a constraint using numeric index or a requirement to use string indexes ? – Allende Mar 11 '14 at 06:04
  • Do you need to keep the string indices? If you won't use them in your code, you can just reformat them as regular arrays and access them using the indices that you want, check your code and make sure you need them, otherwise, any of the answers we provide will work – Lu Roman Mar 11 '14 at 06:14

8 Answers8

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]);
Airy
  • 5,484
  • 7
  • 53
  • 78
  • This looks promising. Let me try it please –  Mar 11 '14 at 06:23
  • @CodeDevil Out of curiosity, what's different about this answer compared to mine? – Ja͢ck Mar 11 '14 at 06:45
  • @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. –  Mar 11 '14 at 07:30
  • @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? – Ja͢ck Mar 11 '14 at 07:38
  • Hold on I just removed. Let me make again. I really appreciate what you suggest. Wait please –  Mar 11 '14 at 07:42
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.

anirudh
  • 4,116
  • 2
  • 20
  • 35
  • 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 –  Mar 11 '14 at 05:39
  • 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 – Lu Roman Mar 11 '14 at 05:44
  • Are you sorting based on the indices or the values of the array? – anirudh Mar 11 '14 at 05:48
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

Community
  • 1
  • 1
rjcarr
  • 2,072
  • 2
  • 22
  • 35
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.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
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

CJ Ramki
  • 2,620
  • 3
  • 25
  • 47
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']);
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

Girish
  • 11,907
  • 3
  • 34
  • 51
  • 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 –  Mar 11 '14 at 05:54
  • @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. – Lu Roman Mar 11 '14 at 05:59
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

Lu Roman
  • 2,220
  • 3
  • 25
  • 40
sunny
  • 1,156
  • 8
  • 15