0

I need to change the index value in javascript

let say

var fruits = ["Banana", "Orange", "Apple", "Mango"];

with index 0-banana,1-Orange,2-Apple,3-Mango

What I want is to change these index values say 345-Banana,346-Orange,347-Apple, 348-Mango .

let me know if there is any quick way to do it , it will reduce some of my conversion code .. Otherwise I have to keep track of index (0,1,2,3) to values(345,346...)

I will store index value in my db, array value is just to display on UI (just like select box)

4
  • 1
    You're sure an object wouldn't be more suitable than an array for that ? Commented Mar 28, 2014 at 6:08
  • I m using some third party tool for UI ,that method takes only array and array index sets as the value to input field . So Just I thought if changing index so everything falls into place Commented Mar 28, 2014 at 6:11
  • 1
    jsfiddle.net/adeneo/gXSZ2 Commented Mar 28, 2014 at 6:11
  • 2
    But jsfiddle.net/adeneo/gXSZ2 is not a good approach Commented Mar 28, 2014 at 6:32

4 Answers 4

2

So why are you using Array. Use Map and give any custom key(index) value.

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

Or if not want to use Map, don't change the index just set the value of input field by

<input type="" value="<any base value like 350>+index"/>

I think this can help.

Sign up to request clarification or add additional context in comments.

3 Comments

I m using some third party tool for UI ,that method takes only array and array index sets as the value to input field . So Just I thought if changing index so everything falls into place
@ULLASK I think you wrote comment in wrong answer. According to my answer, you don't have to change the array index just customize the value field of input element.(see the answer)
ya ya by mistake I put that comment ..I removed it now
1

you need to use associative array.

var fruits= new Array();
fruits['345'] = 'banana';
fruits['346'] = 'Orange';
fruits['347'] = 'Apple';
fruits['348'] = 'Mango'; 

for (var i in fruits) {
    alert('index is: ' + i + ', value is: ' + fruits[i]);
}

Comments

0

use enum like :

var fruits = { 345 : "Banana", 346 : "Orange",347 : "Apple", 348 : "Mango"};

console.log(fruits[345]);

Comments

0

Give the Fruits array a starting index

let fruits = new Array();
fruits[345] = "banana";   // initial index
fruits.push("orange" , "apple" , "mango")
console.log(fruits[346]); // orange

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.