js: add element at the start of an array [duplicate] - javascript

This question already has answers here:
How can I add new array elements at the beginning of an array in JavaScript?
(12 answers)
Closed 10 months ago.
Let´s say I have this array:
let array = ["somevalue", "anothervalue"]
So what I wanted to da was to add a value, for example:
let foo = {bar: true} and add this value at index 0, but not overwrite the old value, rather kind of 'push' the rest of the values back. I´ve heard of array = [foo, ...array] but I am not quite sure what it does and how and when to use it.
Anyone any ideas?

let array = ["somevalue", "anothervalue"]
let foo = {bar: true}
array.unshift(foo);
console.log(array); // prints [{bar: true}, "somevalue", "anothervalue"]
Similarly, the shift() method removes the first item in the array.

It simply append the foo in front of array. so array will become
[{bar: true}, "somevalue", "anothervalue"]
Alternate :
You can also use unshift, it also append data at index 0, eg.
let array = [2, 3, 4]
array.unshift(1)
console.log(array) /// output : [1, 2, 3, 4]

Ok,
let arr = [1,2]
let foo={bar:true}
arr=[foo].concat(arr)
also what you already know works
arr=[foo, ...arr]
That's it

Related

what's wrong with this sort function? javascript [duplicate]

This question already has answers here:
Why does Array.prototype.push return the new length instead of something more useful?
(6 answers)
Closed 1 year ago.
I want to find out the index of the element which is the lowest number in the array.
For ex: function getIndexToIns([3, 2, 10, 7], 4) will return 2 because if 4 is inserted into the array, the array should be [2, 3, 4, 7, 10] following ascending order. And 4 has the index of 2.
And my code snippet is as below and it shows error "TypeError: newArr.sort is not a function"
function getIndexToIns(arr, num) {
newArr = arr.push(num);
newArr.sort((a, b) => a-b);
return newArr.indexOf(num)
}
getIndexToIns([2, 10, 4], 50);
console.log(getIndexToIns([2, 10, 4], 50))
What is wrong in my code snippet???
.push() modifies the array in place, it does not return a new array. So newArray isn't an array.
You can create a new array with something like:
let newArr = [...arr, num];
Or perhaps:
let newArr = arr.concat([num]);
Welcome.
Remove newArr in newArr = arr.push(num); to become
arr.push(num);
Push method doesn't return the array itself but the new length. Ref
See documentation for Array.prototype.push():
The push() method adds one or more elements to the end of an array and
returns the new length of the array.
On top of that, push and sort methods mutate your original array. You should define your newArr like this:
const newArr = [...arr, num];
Then you can sort it and find out the index of element like you do it now.

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.

pushing an array into another array

I have the following arrays.
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3=[];
How would I push arr1 and arr2 into arr3 such that the result is:
arr3=[[1,2,3],[4,5,6]];
not
arr3=[1,2,3,4,5,6];
which is produced when using the .concat method.
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3=[];
arr3.push(arr1,arr2);
console.log(arr3);
var arr1=[1,2,3];
var arr2=[4,5,6];
var arr3 = [arr1,arr2];
console.log(arr3);
arr3.push(arr1);
arr3.push(arr2);
will do the work.
Anyway just follow http://www.w3schools.com/jsref/jsref_push.asp for further clarifications.
Hope this helps.
You can use push() like in the other answers or this:
var arr1 = [1,2,3];
var arr2 = [4,5,6];
var arr3 = [arr1, arr2];
console.log(arr3);
As others users have posted, the solution at your problem is use .push() method, but i would try to give you more information about these two methods.
I suggest you to read this article, is very useful for me; I recap the main information for you below.
PUSH METHOD
Push method is used when you want add one or more elements, that were input arguments, to the array that invoked the method.
A simply example is the following:
var first_array = [1, 2, 3];
var result = first_array.push(4, 5, 6);
console.log(result); // 6
console.log(first_array ); // [1, 2, 3, 4, 5, 6]
The one thing is not immediately apparent is that it returns the length of the array after adding the new values, not the modified array. (check third line: console.log(result);)
CONCAT METHOD
While push alters the array that invoked it, concat returns a new array with the original array joined with the array/s or value/s that were provided as arguments.
There are a couple of the things to note about concat and how it creates the returned array.
Both strings and numbers are copied into the array, which means that they if the original value is changed, the value in the new array will be unaffected.
This is not true for objects.
Instead of copying objects into the new array, the references are copied instead. This means that if the values of objects change in one array, they will also be changed in the other array, as they are references to the objects not unique copies.
A simply example is the following:
var test = [1, 2, 3]; // [1, 2, 3]
var example = [{ test: 'test value'}, 'a', 'b', 4, 5];
var concatExample = test.concat(example); // [1, 2, 3, { test: 'test value'}, 'a', 'b', 4, 5]
example[0].test = 'a changed value';
console.log(concatExample[3].test); // Object { test: "a changed value"}
example[1] = 'dog';
console.log(concatExample[4]); // 'a'
I have created a fiddle for you with this example.
I hope that will be helpful

How to get value at a specific index of array In 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

Categories

Resources