1

I'm trying to understand what an associative array really is and what steps are needed to acquire one. I have seen many explanations that are totally different.

I have tried testing it out on my own but can't seem to really get it in the end.

var array = ["one", "two", "three"];
var test = array["one"];
console.log(test);

I expected for it to target the index in which the string "one" is in, but an error occurs.

pomson2000
  • 11
  • 1
  • If you are trying to use a String to get a particular property, you probably mean [`Object`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object), not an `Array`. – zero298 May 21 '19 at 14:54
  • 1
    What's the question here? Are you actually looking for a definition, or a solution to a problem? Why is it tagged with `split` and `query-string`? – isherwood May 21 '19 at 14:54
  • 1
    Possible duplicate of [Create Associative array in Javascript](https://stackoverflow.com/questions/38339531/create-associative-array-in-javascript) – isherwood May 21 '19 at 14:56
  • Or https://stackoverflow.com/questions/7674922/does-javascript-have-associative-arrays. – isherwood May 21 '19 at 14:56
  • Actually you should call the array this way: `console.log(array[1]);` if you want different behaviour, you could do: `array["one"] = "one"` and then call `array["one"]`: `console.log(array["one"]);`. – Barrosy May 21 '19 at 14:56
  • you can append anything to any object (include array). you don't actually increase the length this way. – apple apple May 21 '19 at 14:56

8 Answers8

2

You are likely looking for a JavaScript Object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. Unlike Arrays, which use square brackets [] for declaration, Objects use curly braces {} (please note that there are some exceptions).

Try to think of an Object as an associative array:

const arr = {one: 1, two: 2, three: 3};
console.log(arr['one']);
console.log(arr.one);

It is worth noting that Array's in JavaScript are technically objects.

The JavaScript Array object is a global object that is used in the construction of arrays; which are high-level, list-like objects.

The main difference between Array's and Object's is that Arrays are numerically indexed.

const arr = ['fooValue', 'barValue'];
const obj = {foo: 'fooValue', bar: 'barValue'};

console.log('arr: ', arr[0], arr[1]);
console.log('obj: ', obj.foo,  obj.bar);

It is worth noting, that unlike primitive types in JavaScript, Object's (and Array's, which are also Object's) are passed by reference, so extra care is needed when attempting to copy the object.

function test(obj) {
  obj['oops'] = 'this will modify the object';
}

const obj = {one: 1, two: 2, three: 3};
test(obj);
console.log(obj); // Object was updated

To avoid accidentally mutating your object, you will have to create a new instance of the object before performing operations on it. There are multiple ways to accomplish this:

Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33
1

I'm trying to understand what an associative array really is...

JavaScript doesn't have associative arrays in the sense that, for instance, PHP does. JavaScript has:

  • Arrays, which are (effectively) numerically indexed (see my blog post for why I said "effectively")
  • Objects, which are collections of properties that have names, which are either strings or Symbols (and which have other features, like inheritance)
  • Maps, which are collections of key/value pairs where the keys can be any type (not just strings or Symbols)

Arrays

To find the index of an entry in an array, typically you use indexOf (for an === match) or findIndex if you want to provide a predicate function.

var array = ["one", "two", "three"];
console.log(array.indexOf("one")); // 0

Objects

If you wanted, you could create an object that mapped strings to numbers:

var obj = {"one": 1, "two": 2, "forty-two": 42};
console.log(obj["forty-two"]); // 42

Maps

Similarly, a Map could do that:

var map = new Map([
    ["one", 1],
    ["two", 2],
    ["forty-two", 42]
]);
console.log(map.get("forty-two")); // 42
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Associative arrays are used to associate something throughout an array. You can use this with the query string for example:

In order to attain the information from a forum submitted, you need to put the user data into an associative array.

You would start by getting the query string as follows:

var queryString = window.location.search;
queryString = queryString.substring(1);

The reason why I did substring(1) is so we could remove the '?' at the beginning.

Once you have the query string of the website, you'd need a loop to separate the values of data received:

while (queryString.indexOf("+") != -1)
    queryString = queryString("+", " ");

This will replace all the '+' signs in the string to spaces, making you get the values without the '+' signs. You'll have "Name=John" for example.

Now we need to split the '&'s from the string. We also need to make an array ready for the data from the user.

var array = queryString.split("&");
var userData = [];

Afterwards, make a for loop in order to target however amount of data submitted and to attain it individually while storing it into the array:

for (let x = 0; x < array.length; x++) 
{
    var equalSign = array[x].search("=");
    var theKeyValue = array[x].substring(0, equal);
    var userDataValue = array[x];
    userDataValue = decodeURIComponent(userDataValue); //Puts symbols back
    userData[theKeyValue] = userDataValue;
}

This is just an example to follow up with the usage of associative arrays, hopefully this helps. :)

0

An associative array is a data structure, a data collection, which has the scope of associate a list of key to respective values (key: value).

You can read in Wikipedia here, that are example of associative array for example: Map, Dictionary, etc.

Sample of associative array are also PHP indexed array, e.g.:

$cars[0] = "Volvo"; 
$cars[1] = "BMW";
$cars[2] = "Toyota";
DAme
  • 697
  • 8
  • 21
0

See Wikipedia.

It is a data structure when you can look up a value by a key. This is typically implemented in JS using a Map or an Object.

const data = new Map([
    ['foo', 'one'],
    ['bar', 'two']
]);

console.log( data.get("bar") );

I expected for it to target the index in which the string "one" is in, but an error occurs.

You are attempting to look up the index of a property in an array by its value.

That has nothing to do with associative arrays and is achieved with the indexOf method.

var array = ["one", "two", "three"];
var test = array.indexOf("one");
console.log(test);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

An associative array, is essentially a hashmap, or an array that associates relationships.

For example if I was to build an associative array for fruits let's say to prices it would look like.

const arr = {'apple': 1, 'orange': 2, 'pear': 3};

console.log(Object.keys(arr));
console.log(Object.values(arr));
Mike Tung
  • 4,735
  • 1
  • 17
  • 24
0

Unlike other languages, array in Javascript are not limited by having only numeric indices. They can act as hashes as well (i.e. having a string as a key). An associative array is one where you set the key to be a non-numeric value.

By default, and in the example you provided, ascending numeric values are assigned to each member of the array. I.e.

var array = ["one", "two", "three"];

is equivalent to

var array = [];
array[0] = 'one';
array[1] = 'two';
array[2] = 'three';

An associative array would be one where instead of numeric values you assign a different value:

var array = [];
array['one'] = 'one';
array['two'] = 'two';

However this brings a few caveats in itself and it considered bad practice and the arrays become harder to manage. In cases like there it would be better to use either an object or a Map.

Vasil Dininski
  • 2,368
  • 1
  • 19
  • 31
-1

That's not an associative array, that's just a regular array, filled with text.

An associative array example (you can also use object syntax like Miroslav's answer):

var stuff = [];
stuff['one'] = "hello 1";
stuff['two'] = "hello 2";
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176