Destructuring Array in ReactJS - javascript

Is there any way that I'm missing do this operation using destructuring an array.
My Array
const arr1 = [1,2,3,4,5,6,7,8,9,10]
and I have a variable rest, arr2 and range=5. And I want first range which is 5 elements from the array and rest of the elements in rest variable. The way I try it to be
[arr2,...rest] = arr1
In this case, arr2 will have output 1 and rest have the rest of the array. Is there any way I can have first 5 elements in arr2

rest = arr1.slice()
arr2 = rest.splice(0, range)

That's not practical but just for fun you can do that (don't use it in real code though)
const [arr2, rest] = [arr1.slice(0, range), arr1.slice(range)]

Related

how to push into an index of an array without splice

splice is time complexity O(n);
I tried this version instead of splice:
which has added space complexity but i think less time complexity.
let arr = [0,1];
arr[5] = 5;
// i need to push numbers into this index only-not to the whole array
// push wont work on a 1d array but will work on 2d array
arr[5] = [[], 5];
// now it is possible to push into this index
arr[5].push(15,125,1035);
// remove the unnecessary empty cell []
arr[5].shift();
console.log(arr) // result [0,1,[5,15,125,1035]]
So is this worse than splice, or better(in terms of time complexity)?
EDIT:
this is a bad take of the answer given, my problem was i didn't understand why you couldn't push into an index of an array.
when you try:
arr = [1,2,3,4]
and then arr[1].push(2.5);
you would get an error since you try and push into a primitive(number and not an object/array).
My mistake was that i thought JS just doesn't allow it.
If you want result [5,15,125,1035] with simply this way.
let arr = [5];
arr.push(15,125,1035);
console.log(arr)
Javascript leaves the underlying implementation of arrays up to the runtime, so the answer will depend on implementation used: How are JavaScript arrays implemented?
but I will assume this array is entirely a flat array.
Pushing to the end of an flat array is only O(1) if the array has space for more elements. Otherwise the array needs to be reallocated which is O(length_of_array). However it should still be faster than splicing on every insertion.
If you want O(1) insertion speed then you could append to the end of a doubly linked list instead, however this is at the cost of space and lookup/iteration speed.
the simpler answer i was looking for is by #Gerardo Furtado
let arr = [0,1,2,3,4,5];
arr[5] = [5];
arr[5].push(15,125,1035);
console.log(arr) // result [0,1,[5,15,125,1035]]

push 1D array to 2D array in first position with javascript [duplicate]

This question already has answers here:
JavaScript: How to join / combine two arrays to concatenate into one array?
(3 answers)
Closed 4 years ago.
i tried to push an array to other array in specific order
with this javascript code :
var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
console.log(arr1.splice(0,-1,arr2));
its reutn [];
my desire rusult : ["1","2","3","A","B","C","D","F"]
please any body show me how to achieve my desire result with splice function
ps : i can achieve this with loop
Thx
EDIT: sorry, My question was misleading. This is my actual condition:
arr1 :[["A","B","C"],["D","E","F"]]
arr2 :["1","2","3"]
Expected output : [["1,"2","3","A","B","C"],["1","2","3","D","E","F"]]
I have tried:
arr1.map(function(e) {
return e.splice(0, -1, arra2)
});
but I got: [],[]
You can use Spread syntax like this const result = [...arr2, ...arr1];
Code:
const arr1 = ["A","B","C","D","E","F"];
const arr2 = ["1","2","3"]
const result = [...arr2, ...arr1];
console.log(result);
Since other solutions creates a new array as result, we could use an approach by modifying in-place your original array by using unshift method in combination with spread syntax.
var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
arr1.unshift(...arr2);
console.log(arr1);
Do you have to use splice? The concat methods does exactly what you want to achieve.
var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
var result = arr2.concat(arr1);
console.log(result);
// If you're okay with using spread syntax (doesn't work in IE), you could just:
console.log([...arr2, ...arr1]);
Spliche works for the given array and if you like to add the values of arr2 at the beginning of the array, then you could splice the array with a spreaded array.
Array#splice returns the array which ts taken out of the given array by the count of the second parameter, which id zero here, and not -1 whcih makes no sense.
var arr1 = ["A", "B", "C", "D", "E", "F"],
arr2 = ["1", "2", "3"]
arr1.splice(0, 0, ...arr2); // returns []
console.log(arr1);
From docs, return value of Array.splice is
An array containing the deleted elements. If only one element is
removed, an array of one element is returned. If no elements are
removed, an empty array is returned.
It will not return the updated array and as you are not removing any element, it will return an empty array.
To add some entries using splice at a particular index, you can try following.
var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
arr1.splice(0,0, ...arr2);
console.log(arr1);

Javascript array in array - first index is always overwritten

I have a problem with my JS function. For simplification, I want to fill an array (arr1) with n other arrays (arr2). In my loop I use a counter for the current postion in arr1 (cant use arr1.push for a reason). If I log all my arr2's in arr1 they are all the same, always the last one that was added. So I wrote a basic script to test it. I always log the first element and incement the counter.
I'm new to JS, is there some huge misunderstanding I don't get?
function test(){
var arr1 = [];
var arr2 = [];
var counter=1;
arr2[0]="first";
arr2[1]="first";
arr2[2]="first";
arr1[0]=arr2;
arr1[0].forEach(function(elem){console.log(elem);});
for (var i = 0; i < 10 ; i++) {
arr2[0]=counter;
arr2[1]=counter;
arr2[2]=counter;
arr1[counter]=arr2;
arr1[0].forEach(function(elem){console.log(elem);});
counter++;
}
}
<button onclick="test()">Click</button>
You can try to use the spread operator.
arr1[0]=[...arr2];
arr1[counter]=[...arr2];
An array is a reference type, so you always refer to the base, you don't put a copy of it inside of arr1 but a reference to the arr2.
You want a copy of arr2 to be assigned to arr1.
You can do this by creating a new Array, or more modern the ... spread operator
As Pointy said it, it just referenced the arr2 and doesn't create a copy.
So you need to
arr2=new Array();
at the beginning of the loop.

Copy substring of string array into new array in Javascript

I am looking to copy the substring of a string array into a new array without creating references. This is giving me a headache yet this should be fairly simple.
I tried NewArray[n] = OldArray[n].substr(x,y).slice(0) inside a loop and does not work. (I need to do a NewArray.sort() afterwards).
For the sake of example, say I got an OldArray with 2 elements:
['River', 'Lake']
I want the new array to be made of the first 2 characters (substring) of the old one such that:
['Ri', 'La']
copy the substring of a string array into a new array without creating references
Strings are primitive values in JavaScript, not Objects. There will be no reference when assigning the values of the old into the new array, especially when creating new strings with substr. The slice(0) you've used is superfluous when used with strings, and not necessary on arrays in your case, too.
Your code should work:
var oldArray = ["River", "Lake"];
var newArray = [];
for (var i=0; i<oldArray.length; i++)
newArray[i] = oldArray[i].substr(0,2);
// newArray: ["Ri", "La"]
This worked for me. Thanks #Bergi
const newArray = oldArray.map( str => str.substr(0,2) );

How do array sizes work in Javascript

In JavaScript, if you set an array to be of size 5 ( var foo = new Array(5); ), is this just an initial size? Can you expand the number of elements after it is created. Is it possible to do something like this as well - arr = new Array() and then just assign elements one by one? Thanks in advance :-)
Yes it is just an initial size, and it is not required. If you don't use a single number, you can immediately populate.
It is also more common to use the simpler [] syntax.
var arr = ['something', 34, 'hello'];
You can set (or replace) a specific index by using brackets:
arr[0] = "I'm here replacing whatever your first item was";
You can add to the end by using push:
arr.push('add me');
There may be faster performance in some browsers if you do it like this instead:
arr[arr.length] = 'add me';
You can add something at any index.
You can remove an item completely using splice:
arr.splice(0, 1); // remove first item in the array (start at index 0, with 1 being removed)
When you give a new array an explicit size in javascript (using new Array(5)), you populate each index with value of undefined. It is generally considered better practice to instantiate using the array literal [] expression:
var arr = [];
Then, you can push new elements using push()
var arr = [];
arr.push('first value'):
arr.push('second value'):
Check out the MDC Array documentation for more info: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Theres a few ways to declare and put values in an array.
First like what you want to do,
var myarr = new Array();
myarr[0] = 'element1';
myarr[1] = 'element2';
myarr[2] = 'element3';
Second way is to define them
var myarr =new Array("element1","element2","element3");
and third is similar to the second
var myarr =["element1","element2","element3"];
You can also check out https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array for a little more information about using the arrays as well. You could use push and pop if you wanted to as well.
If you use jquery or mootools they also have built-in functions to perform on arrays,
http://api.jquery.com/jQuery.each/ for instance.
Have a look at http://www.w3schools.com/js/js_obj_array.asp
var myCars=new Array(); // regular array (add an optional integer
myCars[0]="Saab"; // argument to control array's size)
myCars[1]="Volvo";
myCars[2]="BMW";
Check the documentation for Array, but the simple answer to your question is yes.
var arr5 = new Array(1, 2, 3, 4, 5); // an array with initial 5 elements
var arr = new Array(); // an array without initial
You can also use array literals:
var arr5 = [1, 2, 3, 4, 5];
var arr = [];
Arrays are dynamic in JavaScript. You don't have to initialize them with a certain length. In fact you should use the literal notation [] because of the Array constructor's ambiguity:
If you pass only one parameter to Array, it will set the array length to this parameter. If you pass more than one parameter, these elements are added to the array.
How is the size of the array determined?
The size of an array is the highest index + 1. This can be quite confusing. Consider this:
var arr = [];
arr[41] = 'The answer?';
console.log(arr); // [undefined, undefined, ..., 'The answer?']
console.log(arr.length) // 42
You can even set the length yourself by assigning a number to .length:
arr.length = 99;
If you now add a new element using arr.push(), it will get the index 100 and the length will increase. Whenever you add an element to the array via an index, it is tested whether arr.length is smaller than the index and updated accordingly. But it does not get smaller.
So in fact what var arr = new Array(5) is doing is setting the length of the array to 5. Nothing else.
For more information about creating and populating arrays, I suggest to read about it in the MDC JavaScript Guide.

Categories

Resources