How to swap two elements of an array with empties in JavaScript? - javascript

I have an array and I want to swap two elements in the array. If the array is non-empty, I can simply do:
const swap = (arr, a, b) => {
const temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
}
and the function can correctly swap the value of the index a and b in the array arr.
However, if the array has some empty elements, such as [1, , , ,], and the result of the swap will be [undefined, empty, 1, empty], while the expected result should be [empty × 2, 1, empty]. So how do I modify the swap function so that the result will be correct. Or is there any way to make a specific index to be empty in an array?
Also failed:
const swap = (arr, a, b) => {
const temp = arr[a]
arr.splice(a, 1, arr[b])
arr.splice(b, 1, temp)
}
Original Problem:
I have an array let arr = [1, , , ,] (which will show [1, empty × 3] in console) with length 4, and I want to move the first element to the third, that is: [empty × 2, 1, empty]. How do I achieve that?
I have tried splice and directly assign value to the array but they won't work.

You do need splice - combined with shift to get the first item
let arr = [1, , , ,]
console.log(arr)
arr.splice(2, 0, arr.shift());
console.log(arr)

Related

add 1 to a single element in an array

There is an array containing numbers and I want to increment only one number in the array
let array = [1, 3, 5]
// just add 1 in the second element of the array and return that array
// array = [1, 4, 5]
Both array[1]++ and array[1] = array[1] + 1 will work.
If you want you can increment another number using the Push(); method:
let array = [1,2,3];
array.push(yourNumber);

Return the biggest number in the array (array contains a string)?

I dont understand why my code is not working, when I read it logically I feel that it should work, but what it does is return 3,4,2 as opposed to the highest number of the 3 (i.e. 4)
const array2 = ['a', 3, 4, 2] // should return 4
for(items of array2){
if(items > 0) {
console.log(Math.max(items));
}
What am I doing wrong? What have I misinterpreted? Please don't give me the answer, just tell me why my logic does'nt work
in for-loop, items is just one item actually. Each time, you print the current item. it is basically the same thing with this
const array2 = ['a', 3, 4, 2] // should return 4
for(items of array2){
if (items > 0) {
console.log(items);
}
}
you can do it with this only
const array2 = ['a', 3, 4, 2] // should return 4
console.log(Math.max(...array2.map(s => +s || Number.MIN_SAFE_INTEGER)));
check out: https://stackoverflow.com/a/44208485/16806649
if it was integer-only array, this would be enough:
const array2 = [3, 4, 2] // should return 4
console.log(Math.max(...array2));
You just need to filter the array.
Below example I am using filter() method of array and then just pass that filteredarray to Math.max() function.
isNan() function returns false for valid number.
Math.max(...filteredArr) is using spred operator to pass the values.
const arr = ['a', 3, 4, 2];
const filteredArr = arr.filter(val => {
if (!isNaN(val)) return val;
})
console.log(Math.max(...filteredArr));
I don't think you need the "For(items of arr)" instead just if the length of the array is greater than 0, then console.log(Math.max(...arr) should work.
See document ion below:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
It is returning 3,4,2 because you are taking array2, and iterating through with each individual element of the array. items is not the entire array, it is the individual element and that is why Math.max of an individual element is just getting the same value.
just you need fliter you're array then get max value, also in arrayFilters function use to removes everything only return numbers of this array
function arrayFilters(array){
const number = array.filter(element => typeof element === 'number')
return number;
}
function getMaxValue(number){
return Math.max.apply(null,number)
}
const arr = ['a',2,3,4];
console.log(getMaxValue(arrayFilters(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);

Categories

Resources