Differences in array sorting behavior in Chrome and Internet Explorer

I am facing a challenge with a large JavaScript array that contains about 1000 student names. Each element in the array consists of a student's ID number as its key and the student's name as its value. Here is an example:

student_array['2312'] = 'Bloggs, Joe';
student_array['332'] = 'Carter, John';
student_array['9423'] = 'Davies, David';

The array is arranged in order of the array value. I then create a select box by iterating over the array and generating an option for each value. The key from the array serves as the option value, while the array value becomes the option text.

This is the snippet of my JavaScript code used to create the select box:

var student_select = '<select name="student_id" id="student_id">';

for(x in students_array)
{
    student_select += '<option ' + (student_id==x ? 'selected="selected"' : '') + ' value="' + x + '">' + students_array[x] + '</option>';
}

student_select += '</select>';

In Internet Explorer 8, everything works fine, and the options in the select box are sorted by the value. However, in Chrome, the options are ordered by the key instead, which makes searching for a specific student name challenging.

Question: Is there a way to make Chrome order the select box options by array value rather than by the key?

Answer №1

When using a for..in statement, the order in which elements are iterated over is not guaranteed. Internet Explorer may return them in the order they were added, while Chrome might optimize and return them in numeric order.

If the order of elements matters to you, it is recommended to use an array and handle it correctly.

Here's a suggestion:

var student_array = [
  { id : 2312, name : 'Bloggs, Joe' },
  { id : 332, name : 'Carter, John' },
  { id : 9423, name : 'Davies, David' }
];


var student_select = '<select name="student_id" id="student_id">';
for (var i=0; i<student_array.length; i++) {
    student_id = student_array[i].id;
    student_name = student_array[i].name;
    student_select += '<option ' + (student_id==x ? 'selected="selected"' : '') + ' value="' + student_id + '">' + student_name  + '</option>';
}

student_select += '</select>';

DEMO: http://jsbin.com/IXaCETEw/1/edit

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving object information in the constructor using Angular and Typescript

When attempting to access an object's data within a constructor, it results in an "undefined" object. Even though it functions properly in the ngOnInit() function, the data which is about to be reset is required every time the component is initiated. ...

ngmodelchange activates when a mat-option is chosen in Angular Material

When a user initiates a search, an HTTP service is called to retrieve and display the response in a dropdown. The code below works well with this process. However, clicking on any option in the dropdown triggers the 'ngmodelchange' method to call ...

Using ASP.NET to retrieve data with AJAX and pass parameters to a web method

Looking for assistance with a web method I have created: [WebMethod] [ScriptMethod(UseHttpGet = true)] public static string test(string Name, int? Age) { return "returned value"; } Below is the ajax call I am attempting: $.ajax({ type: "GET", ur ...

How do I send a jQuery table object to a web worker using Javascript?

I have an HTML table with various columns and rows that can be edited by users directly. Whenever a user makes changes to the table, I need to calculate certain sums on the rows of the table. Initially, the function responsible for calculating these sums ...

Tips for choosing this element (using Python)

As I work on getting a selector for the action-button class using Selenium in Python, I am utilizing a Javascript Document QuerySelector. This involves executing some js code via the WebDriver, as demonstrated below: printBtnlast = driver.execute_scrip ...

Create an animation effect where a div increases in height, causing the divs beneath it to shift downward in a

My aim is to create columns of divs where the user can click on a div to see more content as the height expands. I've managed to set this up, but it seems there's an issue with the document flow. When I click on a div in the first column, the div ...

The jquery UI button is displaying too wide even though the padding is set to zero

My goal is to decrease the width of certain jQuery buttons. Though I have attempted to eliminate padding using the code below, there remains a minimum of 5 pixels on either side of the text within my button. .button().css({ 'padding-left':' ...

Issue - The command 'bower install' terminated with Exit Status 1

During my journey through the angular-phonecat tutorial, a frustrating error popped up right after I executed the npm install command: I even checked the log file, but it just echoed the same error message displayed in the console. What's the piece o ...

What is the best way to generate a fresh set of data from a search parameter?

I have received data from an API call that needs to be filtered. I am utilizing Redux instead of local state for this task. Below are the actions I have defined: import ActionTypes from '../constants/ActionTypes'; export const passengersDataAc ...

Utilize the MaterialUI DataGrid to showcase nested object values in a visually appealing

Hey there, fellow coders! I'm currently working on fetching data from an API and displaying it in a data grid using React.js. Here's the format of the data I'm receiving from the API: {data: Array(200)} data : (200) [{…}, {…}, {…}, { ...

"Every time you run mat sort, it works flawlessly once before encountering an

I am having an issue with a dynamic mat table that includes sorting functionality. dataSource: MatTableDataSource<MemberList>; @Output() walkthroughData: EventEmitter<number> = new EventEmitter(); @ViewChild(MatSort, { static: true }) sort ...

Is there a way to identify the browser version that is being used?

I've been on the lookout for a specific code snippet that can help me identify whether the user visiting my website is using Firefox 3 or 4. Thus far, I have only come across code to determine the type of browser without indicating the version. Is th ...

Tips for handling an empty jQuery selection

Below is the code snippet: PHP CODE: if($data2_array[7]['status'] == "OK"){ $degtorad = 0.01745329; $radtodeg = 57.29577951; $dlong = ($lng - $supermercado_lng); $dvalue = (sin($lat * $degtorad) * sin($superm ...

Operating Node.js - leveraging mongoose promises - iterating through

I am currently facing an issue with mongoose in conjunction with node.js. In my model, I only have the group supervisor's ID, but in this route, I also want to add the supervisor's name to a variable (this name is stored in the Group model). I ha ...

React: Perform edits and deletions through a convenient pop-up menu for each item in a list

In my project, I have a list container component that acts as the parent and maps out the list rows. Each list row component, which is the child, contains an item with buttons to toggle a pop-up menu. This menu has options for editing and deleting the item ...

Is there a combination of boolean values present within an array?

I am working with a multidimensional array of strings that resembles the one below. The first column represents IDs, while columns 2-4 represent different variables: #ID Var1 Var2 Var3 comparison = [['1' 'False' & ...

Using Node.js to return JSON data containing base64 encoded images

In my database, I store all images as base64 with additional data (creation date, likes, owner, etc). I would like to create a /pictures GET endpoint that returns a JSON object containing the image data, for example: Image Data [{ "creation": 1479567 ...

Executing Node.js child processes: streaming stdout to console as it happens and running the processes one after the other

Details node: v9.4.0 I am looking for a solution to execute external commands sequentially while monitoring the stdout in real-time. The code snippet below demonstrates my attempt to retrieve all test cases from ./test/ and then running them one after ...

Discover the position of a div relative to another div using ng-drag-drop

I'm currently working on a web application that allows users to create their own identity cards. For this project, I am incorporating the ng-drag-drop library from https://www.npmjs.com/package/ng-drag-drop. The main goal is to obtain the coordinate ...

What is the best way to access a DOM node within a withStyle component?

Currently, I am involved in a react project where my team and I are utilizing Material UI. I encountered a situation where I needed to access the DOM node of another component that was wrapped by a HOC. To achieve this, I attempted using ref in React but o ...