How to get value at a specific index of array In JavaScript? - javascript

I have an array and simply want to get the element at index 1.
var myValues = new Array();
var valueAtIndex1 = myValues.getValue(1); // (something like this)
How can I get the value at the 1st index of my array in JavaScript?

You can access an element at a specific index using the bracket notation accessor.
var valueAtIndex1 = myValues[1];
On newer browsers/JavaScript engines (see browser compatibility here), you can also use the .at() method on arrays.
var valueAtIndex1 = myValues.at(1);
On positive indexes, both methods work the same (the first one being more common). Array.prototype.at() however allows you to access elements starting from the end of the array by passing a negative number. Passing -1 will give the last element of the array, passing -2 the second last, etc.
See more details at the MDN documentation.

Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1].
See Accessing array elements for more info.

You can just use []:
var valueAtIndex1 = myValues[1];

indexer (array[index]) is the most frequent use. An alternative is at array method:
const cart = ['apple', 'banana', 'pear'];
cart.at(0) // 'apple'
cart.at(2) // 'pear'
If you come from another programming language, maybe it looks more familiar.

shift can be used in places where you want to get the first element (index=0) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift mutates the array, which is very different from accessing via an indexer.

Update 2022
With ES2022 you can use Array.prototype.at():
const myValues = [1, 2, 3]
myValues.at(1) // 2
at() also supports negative index, which returns an element from the end of the array:
const myValues = [1, 2, 3]
myValues.at(-1) // 3
myValues.at(-2) // 2
Read more:
MDN, JavascriptTutorial, Specifications

You can use [];
var indexValue = Index[1];

As you specifically want to get the element at index 1. You can also achieve this by using Array destructuring from ES6.
const arr = [1, 2, 3, 4];
const [zeroIndex, firstIndex, ...remaining] = arr;
console.log(firstIndex); // 2
Or, As per ES2022. You can also use Array.at()
const arr = [1, 2, 3, 4];
console.log(arr.at(1)); // 2

Related

How can I "unshift" a 1D array into each el of a 2D array? [duplicate]

I'm trying to push multiple elements as one array, but getting an error:
> a = []
[]
> a.push.apply(null, [1,2])
TypeError: Array.prototype.push called on null or undefined
I'm trying to do similar stuff that I'd do in ruby, I was thinking that apply is something like *.
>> a = []
=> []
>> a.push(*[1,2])
=> [1, 2]
You can push multiple elements into an array in the following way
var a = [];
a.push(1, 2, 3);
console.log(a);
Now in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:
var arr = [1];
var newItems = [2, 3];
arr.push(...newItems);
console.log(arr);
See Kangax's ES6 compatibility table to see what browsers are compatible
When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.
In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))
As one alternative, you can use Array.concat:
var result = a.concat(b);
This would create and return a new array instead of pushing items to the same array. It can be useful if you don't want to modify the source array but rather make a shallow copy of it.
If you want to add multiple items, you can use Array.push() together with the spread operator:
a = [1,2]
b = [3,4,5,6]
a.push(...b)
The result will be
a === [1,2,3,4,5,6]
If you want an alternative to Array.concat in ECMAScript 2015 (a.k.a. ES6, ES2015) that, like it, does not modify the array but returns a new array you can use the spread operator like so:
var arr = [1];
var newItems = [2, 3];
var newerItems = [4, 5];
var newArr = [...arr, ...newItems, ...newerItems];
console.log(newArr);
Note this is different than the push method as the push method mutates/modifies the array.
If you want to see if certain ES2015 features work in your browser check Kangax's compatibility table.
You can also use Babel or a similar transpiler if you do not want to wait for browser support and want to use ES2015 in production.
Easier way is
a = []
a.push(1,2,3)
Another way is
a = [...a, 4,5,6]
if you want to create another array
const b = a.concat(7,8,9)
I had the same doubt and in my case, an easier solution worked for me:
let array = []
array.push(1, 2, 4, "string", new Object())
console.log(array)
// logs [ 1, 2, 4, 'string', {} ]
Pushing multiple objects at once often depends on how are you declaring your array.
This is how I did
//declaration
productList= [] as any;
now push records
this.productList.push(obj.lenght, obj2.lenght, items);
Imagine you have an array of first ten numbers but missing a number, say 6.
You can insert it into the array at the index 5 with the following code
function insert(array, index, obj) {
return [...array.slice(0,index), obj, ...array.slice(index)]
}
let arr = [1,2,3,4,5,7,8,9,0]
arr = insert(arr, 5, 6)
console.log(arr)

Difference between fill and fill map

I came across some code which was filling an array of objects like so:
const getObj = () => {
return {a: 1, b: 2, c: 3};
}
const arr = Array(3).fill(null).map(getObj);
console.log(arr);
However, I'm wondering what the main purpose of fill(null).map(getObj) is? It seems redundant as I can simply write the following and get the same resulting array:
const getObj = () => {
return {a: 1, b: 2, c: 3};
}
const arr = Array(3).fill(getObj());
console.log(arr);
So, I'm wondering if these two lines of code do exactly the same thing or if there is something I'm missing?
The resulting arrays (top array first method with fill + map bottom array is only using map):
Array(3).fill(getObj()) will fill your array with references to the same object, Array(3).fill(null).map(getObj) will create object per element. See the example below:
const getObj = () => {
return {a: 1, b: 2, c: 3};
}
const arr = Array(3).fill(null).map(getObj);
arr[0].b=4;
console.log(JSON.stringify(arr));
const arr1 = Array(3).fill(getObj());
arr1[0].b=4;
console.log(JSON.stringify(arr1))
When it comes to Array.fill it is stated in the documentation that:
When fill gets passed an object, it will copy the reference and fill
the array with references to that object.
So using a Array.fill with objects has somewhat limited application unless you really want to have multiple objects pointing to the same reference. In more than few use cases however that would lead to bugs if not understood.
For the 2nd case where you do Array(3).fill(null).map(getObj) this is one of the ways to create a new array based on a given arbitrary size and at the same time fill it with new objects.
The real need for the fill(null) is due to the fact that calling Array(3) would only do one thing. Create a new array and set its length property to 3. That is it!
let arr = Array(3) // returns new array with its "length" property set to 3
console.log(arr) // [empty × 3] <-- browser console
So that array now has only length and bunch of empty elements. You can't do much with it until it actually has values. Therefore the need for fill so that you give it any value and then map through it to set the values you actually want. Using Array.map and calling each iteration your function guarantees you do not have same references. You could have skipped the fill step and done something like this:
const getObj = () => ({a: 1, b: 2, c: 3})
// using array destructuring
let arr = [...Array(3)].map(getObj)
arr[0].a = 3
console.log(arr)
// using Array.from
let arr2 = Array.from(Array(3)).map(getObj)
arr2[0].a = 3
console.log(arr2)
There are somewhat shorter and get you the exact same result of filling the array with specified length with objects and not references to the same object.
The trick here is that both would "fill" the array after it is defined with undefined values instead, after which the map would fill it with the values we want.

Inserting an object so the array stays sorted

I have an enum of different Steps
export enum StepCategory {
START = 0,
POSITION_1 = 1,
TRANSPORT = 2,
RECEIVER = 3,
END = 4,
NO_STEP_MATCH = 5
}
This will later result in an array, where for every Step I have an object. The Problem is I won't load all the information at once, so i can'tdo a simple for-loop and push each item chronogically. I could be that I first load the value for Step 4, so my array would be:
var array = [{"END" , "POSITIVE"}]
Afterwards I would get the Info for Step 2, then I would have:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
But this is not sorted.
What should I do? Should I declare an array of 6 undefined values
var array = [undefined, undefined, undefined, undefined, undefined, undefined]
This way I wouldn't need any sorting-algorithm after each Update, and can just push the value at the right position.
Just some small Info: I use AngularJS 1, Typescript and Lodash
In plain Javascript, you could sort it with an object and the assigned values of the key.
var StepCategory = { START: 0, POSITION_1: 1, TRANSPORT: 2, RECEIVER: 3, END: 4, NO_STEP_MATCH: 5 },
array = [["END", "POSITIVE"], ["TRANSPORT", "POSITIVE"]];
array.sort(function (a, b) {
return StepCategory[a[0]] - StepCategory[b[0]];
});
console.log(array)
First of all, this is - as someone mentioned in the comments - not syntactically correct:
var array = [{"END", "POSITIVE"}, {"TRANSPORT", "POSITIVE"}]
I assume that this was just a typo writing this question. Additionally if you actually use the enum in your array as key and just left it out for demonstration purposes, I would expect your array of objects to look something like this:
var array = [{StepCategory.END: "POSITIVE"}, {StepCategory.TRANSPORT: "POSITIVE"}]
In order to sort this with LoDash you could use something like this:
var sortedArray = _.sortBy(array, i => Object.keys(i)[0]);
This sorts your array by the value of the first key of each object which refers to your enum value.

Push multiple elements to array

I'm trying to push multiple elements as one array, but getting an error:
> a = []
[]
> a.push.apply(null, [1,2])
TypeError: Array.prototype.push called on null or undefined
I'm trying to do similar stuff that I'd do in ruby, I was thinking that apply is something like *.
>> a = []
=> []
>> a.push(*[1,2])
=> [1, 2]
You can push multiple elements into an array in the following way
var a = [];
a.push(1, 2, 3);
console.log(a);
Now in ECMAScript2015 (a.k.a. ES6), you can use the spread operator to append multiple items at once:
var arr = [1];
var newItems = [2, 3];
arr.push(...newItems);
console.log(arr);
See Kangax's ES6 compatibility table to see what browsers are compatible
When using most functions of objects with apply or call, the context parameter MUST be the object you are working on.
In this case, you need a.push.apply(a, [1,2]) (or more correctly Array.prototype.push.apply(a, [1,2]))
As one alternative, you can use Array.concat:
var result = a.concat(b);
This would create and return a new array instead of pushing items to the same array. It can be useful if you don't want to modify the source array but rather make a shallow copy of it.
If you want to add multiple items, you can use Array.push() together with the spread operator:
a = [1,2]
b = [3,4,5,6]
a.push(...b)
The result will be
a === [1,2,3,4,5,6]
If you want an alternative to Array.concat in ECMAScript 2015 (a.k.a. ES6, ES2015) that, like it, does not modify the array but returns a new array you can use the spread operator like so:
var arr = [1];
var newItems = [2, 3];
var newerItems = [4, 5];
var newArr = [...arr, ...newItems, ...newerItems];
console.log(newArr);
Note this is different than the push method as the push method mutates/modifies the array.
If you want to see if certain ES2015 features work in your browser check Kangax's compatibility table.
You can also use Babel or a similar transpiler if you do not want to wait for browser support and want to use ES2015 in production.
Easier way is
a = []
a.push(1,2,3)
Another way is
a = [...a, 4,5,6]
if you want to create another array
const b = a.concat(7,8,9)
I had the same doubt and in my case, an easier solution worked for me:
let array = []
array.push(1, 2, 4, "string", new Object())
console.log(array)
// logs [ 1, 2, 4, 'string', {} ]
Pushing multiple objects at once often depends on how are you declaring your array.
This is how I did
//declaration
productList= [] as any;
now push records
this.productList.push(obj.lenght, obj2.lenght, items);
Imagine you have an array of first ten numbers but missing a number, say 6.
You can insert it into the array at the index 5 with the following code
function insert(array, index, obj) {
return [...array.slice(0,index), obj, ...array.slice(index)]
}
let arr = [1,2,3,4,5,7,8,9,0]
arr = insert(arr, 5, 6)
console.log(arr)

javascript/jQuery Array concatenation?

I have some simple jQuery code:
var response = Array()
$('.task-list').each(function() {
response.concat(response,$('#' + this.id).sortable('toArray'));
}
);
console.log(response);
The problem I'm having is that I think I'm using concat improperly- the result is an empty array. When I use array push, it works correctly.
You have to set response to the newly formed array, as described in the specification. You currently don't use the return value at all.
The specification says that for .concat, the array is not altered, but the new array is returned:
When the concat method is called with zero or more arguments item1, item2, etc., it returns an array containing the array elements of the object followed by the array elements of each argument in order.
Compare with .push, which says the current array is altered, and that something else is returned instead (the new length):
The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.
So:
response = response.concat($('#' + this.id).sortable('toArray'));
Concat returns the concatenated array, you want this instead
response = response.concat($('#' + this.id).sortable('toArray'));
Simple example
var a = [1,2];
var b = [3,4];
a = a.concat( b ); // result is [1,2,3,4] which is correct
If you do the following
a = a.concat( a , b ); // result is [1, 2, 1, 2, 3, 4] not what you want.

Categories

Resources