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);
Related
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)]
Is there any reason why I canot .push() objects into an Array? Simplified example below.
let myArray = [{x:1},{x:2}];
let myObj = {x:1};
let x = myArray.push(myObj);
console.log(x)
// I'am expecting [{x:1},{x:2},{x:1}] but I get 3
The return value of push is the length of the modified array. It isn't another reference to the same array, nor is it a new array.
If you want to log the array, then console.log(myArray) instead of x.
Simple, push just returns the length of the new array and the array was modified in place. Try:
console.log(myArray)
myArray.push(myObj) returns a number of objects it has. you are displaying the array length. If we print myArray you could see the array of Object.
You should console.log(myArray); The way you do returns the new length of the array, which you assign another reference
DEMO
let myArray = [{x:1},{x:2}];
let myObj = {x:1};
console.log(myArray);
myArray.push(myObj);
console.log(myArray);
Array.push() function is working properly, and it returns the new length of the array
The push() method adds one or more elements to the end of an array and returns the new length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push?v=a
I have two examples:
function myFunction(arr, size) {
// Break it up.
var newArray = [];
var tempArray = arr.splice(0,1);
newArray.push(arr.splice(0,1));
console.log(newArray);
return arr;
}
myFunction(["a", "b", "c", "d"], 2);
And this one:
function myFunction(arr, size) {
// Break it up.
var newArray = [];
var tempArray = arr.splice(0,1);
newArray.push(tempArray);
console.log(newArray);
return arr;
}
myFunction(["a", "b", "c", "d"], 2);
The main difference being the line:
newArray.push(arr.splice(0,1)); // Or newArray.push(tempArray);
Why does the first example return Array[1] and the second example return ["a"]?
I was expecting to get ["a"] regardless of which way I went, can someone possibly help me understand what is happening here?
I was just trying to take the first element of the array by splicing (which I believe returns an array of the removed elements) and push this array onto my "newArray" so I can ultimately have an array containing nested arrays holding each character. I.e. [["a"],["b"],["c"]...]
EDIT: Please ignore the "size" parameter.
EDIT2: Sincere apologies. I'm not worried about the return statement. Stupid of me to forgot to mention. I'm looking at my console.log output. When I run the script and look at the console, that's when I'm getting Array[1] or ["a"].
This is the most important information you need to have in mind: splice changes the original array (read this: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice).
So, let's see your first function. This line:
var tempArray = arr.splice(0,1);
Changes arr, as expected. But, when you do this in the next line:
newArray.push(arr.splice(0,1));
You are changing arr again!
Your second function, on the other hand, changes arr just once:
var tempArray = arr.splice(0,1);
newArray.push(tempArray);
In a nutshell: just count how many times you have a splice in your first function (2 times, changing the original array twice) and how many times you have a splice in your second function (1 time, changing the original array only once).
EDIT: regarding the console.log, newArray is an array with an array, and that's why sometimes you see Array[1]. Do this:
console.log(newArray[0]);
And now you'll see ["a"], ["b"] or whatever.
I want to clone a new array from an existing one and push in an element.
Unfortunately, the existing array is an empty one, so it's like:
[].slice().push(65)
the output of above expression is 1.
Why is it 1?
Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.
If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:
var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
Changing my comment to an answer:
MDN push(): The push() method adds one or more elements to the end of an array and returns the new length of the array.
You need to do it in two steps, not one with that pattern.
var temp = [].slice();
temp.push(65);
console.log(temp);
If you want to do it in one line, look into concat()
var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);
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.