Tagged Questions

451
votes
15answers
266k views

array.contains(obj) in JavaScript

What is the most concise and efficient way to find out if a JavaScript array contains an obj? This is the only way I know to do it: contains(a, obj) { for (var i = 0; i < a.length; i++) { ...
214
votes
12answers
131k views

Length of Javascript Object (ie. Associative Array)

If I have a javascript associative array say: var myArray = new Object(); myArray["firstname"] = "Gareth"; myArray["lastname"] = "Simpson"; myArray["age"] = 21; Is there a built in or accepted best ...
97
votes
9answers
47k views

How to sort an array of javascript objects?

I read in the following JSON using Ajax and store the objects in an array: var homes = [{ "h_id": "3", "city": "Dallas", "state": "TX", "zip": "75201", "price": "162500" }, { ...
141
votes
11answers
130k views

Loop through array in JavaScript

In Java you can use a for() loop to go through objects in an array like so: String[] myStringArray = {"Hello","World"}; for(String s : myStringArray) { //Do something } can you do the same in ...
229
votes
9answers
225k views

Best way to find an item in a JavaScript array? [closed]

Possible Duplicate: array.contains(obj) in JavaScript What is the best way to find if an object is in an array? This is the best way I know: function include(arr, obj) { for(var i=0; ...
35
votes
7answers
10k views

What’s the difference between “Array()” and “[]” while declaring a JavaScript array?

Whats the real difference between declaring an array like this: var myArray = new Array(); and var myArray = [];
254
votes
18answers
180k views

What is the best way to add options to a select from an array with jQuery?

What is the best method for adding options to a select from a JSON object using jQuery? I'm looking for something that I don't need a plugin to do, but would also be interested in the plugins that ...
245
votes
11answers
174k views

JavaScript Array Delete Elements

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method? For example: myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // or ...
67
votes
19answers
56k views

Easiest way to find duplicate values in a JavaScript array

I need to check a JavaScript array to see if there are any duplicate values. What's the easiest way to do this? I just need to find what the duplicated values are - I don't actually need their indexes ...
24
votes
17answers
16k views

JavaScript array difference

Is there a way to return the difference between two arrays in JavaScript? For example: var a1 = ['a', 'b']; var a2 = ['a', 'b', 'c', 'd']; // need ["c", "d"] Any advice greatly appreciated.
22
votes
4answers
3k views

Is Chrome's JavaScript console lazy about evaluating arrays?

I'll start with the code: var s = ["hi"]; console.log(s); s[0] = "bye"; console.log(s); Simple, right? In response to this, Firebug says: ["hi"] ["bye"] Wonderful, but Chrome's JavaScript ...
38
votes
11answers
6k views

How to detect if a variable is an array

What is the best de-facto standard cross-browser method to determine if a variable in JavaScript is an array or not? Searching the web there are a number of different suggestions, some good and quite ...
66
votes
15answers
42k views

Remove empty elements from an array in Javascript

How do I remove empty elements from an array in Javascript? Is there a straightforward way, or do I need to loop through it and remove them manually? Thanks
39
votes
6answers
52k views

How do I split this string with JavaScript?

I have this string 'john smith~123 Street~Apt 4~New York~NY~12345' Using JavaScript, what is the fastest way to parse this into var name = "john smith"; var street= "123 Street"; //etc...
18
votes
8answers
7k views

Find object by id in array of javascript objects

I've got an array: myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'bar'},etc.] I'm unable to change the structure of the array. I'm being passed an ID#, e.g. '45', and I want to get 'bar' for ...
243
votes
3answers
113k views

Checking if an associative array key exists in Javascript

How do I check if a particular key exists in a Javascript associative array? If a key doesn't exist and I try to access it, will it return false? Or throw an error?
120
votes
3answers
69k views

Javascript - Insert Item into Array at a Specific Index

I am looking for a JavaScript array insert method, in the style of: arr.insert(index, item) Preferably in jQuery, but any JavaScript implementation will do at this point because I can't believe the ...
52
votes
8answers
18k views

how to store an Array in localStorage?

If i didn't need localStorage, my code would look like this: var names=new Array(); names[0]=prompt("New member name?"); This works, however I need to store this variable in localStorage and its ...
82
votes
11answers
105k views

How can I create a two dimensional array in JavaScript?

I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc. How do I declare a 2 dimensional array in JavaScript? ...
14
votes
8answers
23k views

Using jQuery to compare two arrays

I have two arrays of JavaScript Objects that I'd like to compare to see if they are the same. The objects may not (and most likely will not) be in the same order in each array. Each array shouldn't ...
30
votes
5answers
9k views

Javascript Array.sort implementation?

Which algorithm does the JavaScript Array.sort() function use? I understand that it can take all manner of arguments and functions to perform different kinds of sorts, I'm simply interested in which ...
12
votes
1answer
221 views

I have a nested data structure / JSON, how can access a specific value?

I have a nested data structure containing objects and arrays. How can I access a specific value? For example: var data = { code: 42, items: [{ id: 1, name: 'foo' }, { ...
42
votes
4answers
25k views

Remove item from array by value

Is there a method to be able to remove an item from an JavaScript array like from this array: var ary = ['three', 'seven', 'eleven']; And I do an function like whereas: removeItem('seven', ary); ...
10
votes
5answers
10k views

Best way to transfer an array between PHP and Javascript

So I have an array of records retreived from a database. The array is in the format; $rows[0]['id']=1; $rows[0]['title']='Abc'; $rows[0]['time_left']=200; $rows[1]['id']=2; $rows[1]['title']='XYZ'; ...
87
votes
11answers
43k views

JavaScript: Check if object is array?

I'm trying to write a function that either accepts a list of strings, or a single string. If it's a string, then I want to convert it to an array with just the one item. Then I can loop over it ...
27
votes
4answers
3k views

Why is array.push sometimes faster than array[n] = value?

As a side result of testing some code I wrote a small function to compare the speed of using the array.push method vs direct addressing (array[n] = value). To my surprise the push method often showed ...
19
votes
7answers
18k views

jQuery min/max property from array of elements

Is there a simple way to find the min/max property from an array of elements in jQuery? I constantly find myself dynamically resizing groups of elements based on the minimum and maximum counterparts. ...
13
votes
2answers
818 views

Array Like Objects in Javascript

I'm wondering how jQuery constructs it's array like object. The key thing I'm trying to work out is how it manages to get the console to interpret it as an array and display it as such. I know it has ...
10
votes
6answers
4k views

What is the difference between an array and an object?

The following two different code snippets seem equivalent to me: var myArray = Array(); myArray['A'] = "Athens"; myArray['B'] = "Berlin"; and var myObject = {'A': 'Athens', 'B':'Berlin'}; ...
8
votes
9answers
15k views

Unique values in an array

I have an array of numbers that I need to make sure are unique. I found the code snippet below on the internet and it works great until the array has a zero in it. I found this other script here on SO ...
3
votes
3answers
575 views

JavaScript Loops: for in vs for

I faced a strange behaviour in Javascript. I get "Object doesn't support this property or method" exception for the removeAttribute function in the following code: var buttons = ...
49
votes
7answers
15k views

Create an empty object in JavaScript with {} or new Object()?

There are two different ways to create an empty object in JavaScript: var objectA = {} var objectB = new Object() Is there any difference in how the script engine handles them? Is there any reason ...
33
votes
4answers
17k views

Javascript, NodeJS: is Array.forEach asynchronous?

I have a question regarding the native Array.forEach implementation of Javascript: Does it behave asynchronously? For example, if I call: [many many elements].forEach(function () {lots of work to ...
89
votes
9answers
36k views

How do you check if a variable is an array in JavaScript?

I would like to check whether a variable is either an array or a single value in JavaScript. I have found a possible solution... if (variable.constructor == Array)... Is this the best way this can ...
40
votes
4answers
941 views

Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?

Given a simple zero based, numerically indexed array: var list = ['Foo', 'Bar', 'Baz']; Many times, I have noticed that when someone suggests looping through variables in an array like this: ...
15
votes
3answers
386 views

Is reading the `length` property of an array really that expensive an operation in JavaScript?

I always assumed caching the length of an array in JavaScript is a good idea (especially in the condition of a for loop) because of the expensiveness of calculating the length of an array. Example ...
14
votes
6answers
939 views

Have I reached the limits of the size of objects JavaScript in my browser can handle?

I'm embedding a large array in <script> tags in my HTML, like this (nothing surprising): <script> var largeArray = [/* lots of stuff in here */]; </script> In this particular ...
11
votes
5answers
25k views

Comparing Arrays of Objects in JavaScript

I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 ...
5
votes
4answers
632 views

Randomizing elements in an array?

I've created a site for an artist friend of mine, and she wants the layout to stay the same, but she also wants new paintings she'd produced to be mixed into the current layout. So I have 12 ...
7
votes
7answers
4k views

Counting occurences of Javascript array elements

In Javascript, I'm trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each unique element, and the ...
5
votes
5answers
2k views

Getter/setter on javascript array?

Is there a way to get a get/set behaviour on an array? I imagine something like this: var arr = ['one', 'two', 'three']; var _arr = new Array(); for (var i=0; i < arr.length; i++) { ...
6
votes
11answers
7k views

What's the best way to loop through a set of elements in JavaScript?

In the past and with most my current projects I tend to use a for loop like this: var elements = document.getElementsByTagName('div'); for (var i=0; i<elements.length; i++) { ...
265
votes
8answers
123k views

Appending to array

How do I append to an array in Javascript?
125
votes
7answers
66k views

How do I remove objects from a javascript associative array?

Suppose I have this code: var myArray = new Object(); myArray["firstname"] = "Bob"; myArray["lastname"] = "Smith"; myArray["age"] = 25; Now if I wanted to remove "lastname"?....is there some ...
16
votes
10answers
18k views

What is the most efficient way to sort an Html Select's Options by value, while preserving the currently selected item?

I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's text, value, and selected properties, but I don't think that javascript's built in ...
9
votes
4answers
43k views

Convert js Array() to JSon object for use with JQuery .ajax

in my app i need to send an javascript Array object to php script via ajax post. Something like this: var saveData = Array(); saveData["a"] = 2; saveData["c"] = 1; alert(saveData); $.ajax({ type: ...
6
votes
3answers
12k views

javascript multidimensional array?

I hope I can make myself clear in English and in what I want to create. I first start with what I want. I want to make a IBANcalculator that can generate 1-n IBANnumbers and also validate a given ...
19
votes
5answers
250 views

Javascript Funky array mishap

function a() { var b = ["b"]; console.log(b); //console.log(b.slice()); b = b.push("bb"); } a(); In a "perfect" world you would think that the console.log would show ["b"], but wildly ...
11
votes
3answers
17k views

Convert Javascript Array to JSON

Hay I have an Array (var cars = []) which hold a few integers. I've added a few values to the array, but i now need to send this array to a page via jQuery's .get method. But i want to send it as a ...
10
votes
5answers
8k views

How to sort an associative array by its values in Javascript?

If I have the associative array: array["sub2"] = 1; array["sub0"] = -1; array["sub1"] = 0; array["sub3"] = 1; array["sub4"] = 0; Then what is the most elegant way to sort (descending) by its values ...

1 2 3 4 5 8
15 30 50 per page