Javascript: Replace everything inside an Array with a new value - javascript

I've got an Array:
var Arr = [1, 4, 8, 9];
At some point later in the code this happens:
Arr.push(someVar);
Here instead of pushing a new value, I want to replace the entire contents of Arr with someVar. (i.e. remove all previous contents so that if I console.logged() it I'd see that Arr = [someVar]
How could this be achieved??

Try:
Arr.length = 0;
Arr.push(someVar);
Read more: Difference between Array.length = 0 and Array =[]?

Try this:
Arr = [somevar];
Demo: http://jsfiddle.net/UbWTR/

you can assign the value just like this
var Arr = [1, 4, 8, 9]; //first assignment
Arr = [other value here]
It will replace array contents.
I hope it will help

you want splice to keep the same instance: arr.splice(0, arr.length, someVar)

You can do like this
var Arr = [1, 4, 8, 9]; // initial array
Arr = [] // will remove all the elements from array
Arr.push(someVar); // Array with your new value

Related

How to combine array within another array using javascript or jquery?

I have an array named arr and within that array, I have another array.My question is, how to combine this two array?
var arr=["1","2","[3,4]","5"]
My output should be like this:
1,2,3,4,5
Thanks in advance!
You could use spread syntax ... with map and JSON.parse methods.
var arr = ["1","2","[3,4]","5"]
var result = [].concat(...arr.map(e => JSON.parse(e)))
console.log(...result)
Considering that you have an actual array and not a string you can flatten like this
var arr=["1","2",["3","4"],"5"]
var flat = [].concat(...arr)
console.log(flat)
You can change it to string and further replace the square brackets using replace(/[\[|\]]/g,''):
var arr=["1","2","[3,4]","5"];
var res = arr.toString().replace(/[\[|\]]/g,'');
console.log(res);
If the question is how to flat an array like this [1,2,[3,4],5] or this [1,[2,[[3,4],5]]] into this[ 1, 2, 3, 4, 5 ] here a pretty general and short solution:
var arr = [1, [2, [[3, 4], 5]]];
var newArr = JSON.parse("[" + JSON.stringify(arr).replace(/\[|\]/g, "") + "]");
console.log(newArr)
Or .flat if browser supports it:
var arr = [1, 2, [3, 4, [5, 6]]];
arr.flat();
console.log(arr)

forEach seems to be working for push() function but didn't work for pop() in JavaScript. can someone tell me what I am doing wrong

//code1
let a= [1, 3 , 4, 6];
[7, 8 , 9].forEach(l => a.push(l));
console.log(a);
// [1, 3, 4, 6, 7, 8, 9 ]
1.it worked for push() function
//code2
let a= [1, 3 , 4, 6];
a.forEach(l => a.pop(l));
console.log(a);
//[ 1, 3 ]
2. didn't work for pop() though
Javascript Array.pop() removes the last element from the array and returns that.
Example:
var arr = [1,2,3]
arr.pop(); // returns 3
Reference
If you want to remove a element with specific value than try something like:
var arr = [1, 2, 3];
var index = arr.indexOf(1);
if (index > -1) {
array.splice(index, 1);
}
var arr = [1, 2, 3, 4];
console.log(arr.pop());
var index = arr.indexOf(2);
if (index > -1) {
arr.splice(index, 1);
}
console.log(arr)
forEach automatically extracts the elements one by one and gives them to you
It starts from the beginning of the array, and does them all.
It doesn't delete elements from the array.
a = [1, 3, 4, 6];
a.forEach(item => console.log(item));
// output is in forwards order
// and 'a' retains original contents
pop() extracts and deletes one element for you
It starts from the end of the array, and does only one.
It deletes the element from the array.
a = [1, 3, 4, 6];
while (a.length > 0) {
console.log(a.pop())
}
// items come out in reverse order
// and 'a' is being emptied so it is [] at the end
Choose your method
Do you want the last element actually removed from the array? This is what you would want if you were implementing a stack, for example. In that case, use ".pop()".
This gets one element from the end of the array and deletes it from the array.
Or do you want to just look at each element in turn from the array (starting at the beginning), without changing the array itself. This is a commoner situation. In this case, use ".forEach"

How to remove an item from a list without distorting the original list

This is what I'm trying to do, I have an array
var arr = [1, 2, 3, 4, 5];
then I want to create a new array each time by removing an item once i.e when i remove item at index 0 i should have [2, 3, 4, 5]and when i remove an item at index 1, I should have [1, 3, 4, 5] and so on till i get to arr.length-1 and each time i remove an item i still want my arr to be intact unchanged
using javaScript I have tried some array methods like splice, slice but all that changes the value of arr
how do i go about it with either javascript or python.
For Javascript, using ES6 array spread operator and slice method,
var new_array = [...a.slice(0, index), ...a.slice(index + 1)];
const cut = (a, i) => [...a.slice(0, i), ...a.slice(i + 1)];
let arr = [2, 2, 2, 4, 2];
console.log(cut(arr, 3));
console.log(arr);
For Python:
array = [1,2,3,4,5];
newarray = [value for counter, value in enumerate(array) if counter != 0 ]
PS each time you will use this list-comprehension, array will not be modified! so basically you will get the same output for newarray.
If you want to have newarray each time removed one element you need to create a function instead of list-comprehension (of course it's possible but will likely be less readable).
For JavaScript:
Try making a copy with slice() (slice returns a shallow copy of the array that you can manipulate without affecting the original array) and then using splice() to remove the value at your desired index:
newArray = slice(arr).splice(index, 1);

Return an array with all the elements of the passed in array but the last

Instructions:
Write a function called getAllElementsButLast.
Given an array, getAllElementsButLast returns an array with all the elements but the last.
Below is my code that will not pass the requirements for the question. I am not sure why this is not correct even though I am getting back all the elements besides the last.
var arr = [1, 2, 3, 4]
function getAllElementsButLast(array) {
return arr.splice(0, arr.length - 1)
}
getAllElementsButLast(arr) // [1, 2, 3]
I think the reason why it's not accepted is because with splice() you change the input array. And that's not what you want. Instead use slice(). This method doesn't change the input array.
var arr = [1, 2, 3, 4]
function getAllElementsButLast(array) {
var newArr = array.slice(0, array.length - 1);
return newArr;
}
var r = getAllElementsButLast(arr);
console.log(r);
console.log(arr);

Store result of array.sort in another variable

This seems like a simple question but I can't find much info on this.
var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = array1;
array2.sort(function(a, b) {
return a - b;
})
Expected behavior: array2 is sorted and array1 is in the original order starting with 4.
Actual result: both arrays are sorted.
How can I sort array1 - while maintaining array1 and storing the results of the sort in array2? I thought that doing array2 = array1 would copy the variable, not reference it. However, in Firefox's console both arrays appear sorted.
That's becasue with var array2 = array1; you're making a new reference to the object, so any manipulation to array2 will affect array1, since the're basically the same object.
JS doesn't provide a propner clone function/method, so try this widely adopted workarround:
var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = JSON.parse(JSON.stringify(array1));
array2.sort(function(a, b) {
return a - b;
});
Hope it helps :)
You can copy a array with slice method
var array1 = new Array(4, 3, 1, 2, 0, 5);
var array2 = array1.slice();

Categories

Resources