Languages

JavaScript - what is the most efficient way to get first item from associative array?

0 points
Asked by:
Kia-H
546

What is the most efficient way to get the first item from an associative array in JavaScript?

Actually I need to get, just the first key of a large associative array.

1 answer
0 points
Answered by:
Kia-H
546

Since associative arrays in JavaScript are objects, there isn't really a first or last element.

You can hope to acquire the order that the elements were saved by the parser and there's no guarantee for consistency.

However, if you want the first key to come up, here is an example function:

// ONLINE-RUNNER:browser;

function getKey(object) {
    for (var property in object) {
        return property;
    }
}


// Usage example

var associativeArray = {
    key1: 'value1',
    key2: 'value2',
};

console.log(getKey(associativeArray));

or if you want to avoid inheritance properties:

// ONLINE-RUNNER:browser;

function getKey(object) {
    for (var property in object) {
        if (object.propertyIsEnumerable(property)) {
            return property;
        }
    }
}


// Usage example:

var associativeArray = {
    key1: 'value1',
    key2: 'value2',
};

console.log(getKey(associativeArray));
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join