Array JavaScript problem. First element go to the last position - javascript

I have function that get array, and return array with power 2 of every array element. This is source code
const firstArr = [1, 2, 3, 7, 4, 9];
function arrayPow(arr) {
const outputArray = [];
arr.forEach(el => {
console.log(el);
outputArray.splice(-1, 0, el**2);
})
return outputArray;
}
console.log(arrayPow(firstArr));
I got this as output:
script.js:8 1
script.js:8 2
script.js:8 3
script.js:8 7
script.js:8 4
script.js:8 9
script.js:14 (6) [4, 9, 49, 16, 81, 1]
Scedule of elments correct in loop. But now in array, there first element, in some reson, stay in the end. I tried to delete "1" from firstArr, then "4" go to the last position.
Why?

Putting -1 in your splice means you insert before the last element in the array. When the array is empty, it simply is added as the only item.
Following, you then insert before the last element of the array, hence every subsequent iteration will add the item as the second last element.
I would just use ES6 magic:
const firstArr = [1, 2, 3, 7, 4, 9];
const arrayPow = (arr) => arr.map(i => i**2)
console.log(arrayPow(firstArr))

Use this code, it will work like charm!
const firstArr = [1, 2, 3, 7, 4, 9];
function arrayPow(arr) {
return arr.map(v => v ** 2);
}
console.log(arrayPow(firstArr));

If I am understanding your question correctly, you want to raise each element in the array by the power of 2? If so, I am unsure why you are splicing the array. You could try the following:
function arrayPow(arr) {
const outputArray = [];
arr.forEach(el => {
outputArray.push(el**2);
})
return outputArray;
}
const test = [1,2,3]
console.log(arrayPow(test))

Related

How to access the last element of an array using destructuring? [duplicate]

This question already has answers here:
Destructuring to get the last element of an array in es6
(17 answers)
Get first and last elements in array, ES6 way [duplicate]
(1 answer)
Closed 8 months ago.
Suppose I have an array like this: [2, 4, 6, 8, 10].
I want to access the first and last element of this array using destructuring, currently I'm doing this:
const array = [2, 4, 6, 8, 10];
const [first, , , , last] = array;
console.log(first, last);
But this is only works with arrays of length 5 and is not generic enough.
In Python I could do something like this:
array = [2, 4, 6, 8, 10]
first, *mid, last = array
print(first, last)
But in JS this is not possible since rest elements should be the last. So, is there some way to do this in JS or this is not possible?
You can use object destructuring and grab the 0 key (which is the first element) and rename it to first & then using computed property names you can grab the array.length - 1 key (which is the last element) and rename it to last.
const array = [2, 4, 6, 8, 10];
const { 0: first, [array.length - 1]: last } = array;
console.log(first, last);
You can also grab the length via destructuring and then use that to grab the last element.
const array = [2, 4, 6, 8, 10];
const { length, 0: first, [length - 1]: last } = array;
console.log(first, last);
Another simple approach to access the last element would be to use the Array.prototype.at method. This is not related to destructuring but it's worth knowing.
const array = [2, 4, 6, 8, 10];
console.log(array.at(-1));
Not necessarily using destructuring, but still concise in my opinion:
const arr = [1, 2, 3, 4, 5];
const [ first, last ] = [ arr.at(0), arr.at(-1) ];
console.log(first, last);
No, you can't use destructuring like that without convoluted workarounds.
A shorter, more readable alternative is to just pop:
const array = [2, 4, 6, 8, 10];
const [first, ...middle] = array;
const last = middle.pop();
console.log(first, middle, last);
Or, just access them by index:
const array = [2, 4, 6, 8, 10];
const first = array[0];
const last = array[array.length - 1];
console.log(first, last);

how to Search for duplicates in list (javascript)?

I try to look for duplicates in the array and get an error, and I glad for any solution for this problem
Attached is code:
let names = itemList[0].getElementsByTagName("span")[0].innerText;
for (i = 1; i < itemList.length; i++) {
if (!(itemList[i].getElementsByTagName("span")[0].innerText in names)) {
names.push(itemList[i].getElementsByTagName("span")[0].innerText);
}
}
You can use indexOf. If the indexOf that item in the array you're trying to push to is -1, that means it doesn't exist, and that you can go ahead and push it in. Otherwise, do nothing. You can also reverse this, and add to the array from the other if it already exists, and do nothing if it doesn't.
Example:
const array = [1, 2, 3, 4, 5, 6, 7, 8];
// We are adding this. Expecting to not add the numbers that are already there
const toPushTo = [1, 10, 5];
const addToArrayIfNotDuplicate = (arr)=> {
arr.forEach(item=>{
toPushTo.indexOf(item) === -1 ? toPushTo.push(item) : null;
})
};
addToArrayIfNotDuplicate(array);
console.log(toPushTo);

map() method mutating the calling Array

map() can't mutate the calling array, instead it returns a new Array with modified values.
But, the following code mutating the original Array, is there any wrong in my understanding?
const arr = [1, 2, 3, 4, 5];
arr.map((num, index, arr1) => {
return arr1[index] = num * 2;
});
console.log(arr); // [2, 4, 6, 8, 10]
Well, you're mutating the original array by passing its reference into the callback function inside map() (arr1) and then manually accessing the indices. It will create a new array if you just return the value from that function.
const arr = [1, 2, 3, 4, 5];
const arr1 = arr.map((num) => {
return num * 2;
});
console.log(arr); // [1, 2, 3, 4, 5]
console.log(arr1); // [2, 4, 6, 8, 10]
The third argument to the callback function of map is the
original/source array on which the map is called upon
The arr and arr1 are both same i.e both are referencing on the same array, You can see it by using console.log(arr === arr1). So what ever you operation perform on the arr1, it gonna affect the arr.
const arr = [1, 2, 3, 4, 5];
arr.map((num, index, arr1) => {
console.log(arr1 === arr);
return num * 2;
});
You can just return num * 2 from the callback function. map internally creates a new array and return it. So you don't have to assign it as
arr1[index] = num * 2
You can also make it one-liner as:
arr.map((num, index, arr1) => num * 2)
const arr = [1, 2, 3, 4, 5];
const result = arr.map((num, index, arr1) => {
return num * 2;
});
console.log(arr); // [2, 4, 6, 8, 10]
console.log(result); // [2, 4, 6, 8, 10]
Array.map creates a new array populated with the results of calling a provided function on every element in the calling array.
Here its specifed that you must call or execute a function on every element of calling array.
What is the issue with your code?
You are not actually calling a function, you are instead updating the original array. If you are looking to create a new array by multiplying each node of the element with 2, you should do something like below.
Working Example
const arr = [1, 2, 3, 4, 5];
const newArray = arr.map((nodeFromOriginalArray, indexOfCurrentElement, arrayFromMapCalled) => {
return nodeFromOriginalArray * 2;
});
console.log(arr);
console.log(newArray);
Lets debug the paremeters inside the map function.
Here we have provided three arguments.
First argument nodeFromOriginalArray: The current element being processed in the array. This will be each node from your calling array.
Second argument indexOfCurrentElement: The index of the current element being processed in the array. Which means, the index of current element in calling array.
Third argument arrayFromMapCalled: The array map was called upon. This is the array on which the map function is getting executed. Please note, this is the original array. Updating properties inside this array results in updating your calling array. This is what happened in your case.
You should not modify your original array, which is the third parameter. Instead, you should return your node multipled by 2 inside map and assign this to a new array. Updating the third paramater inside the map function will mutate your calling array.
When calling map on an array, you provide a mapper with three arguments, an item in the array, it's index and the array itself (as you've represented in your snippet).
map takes the value returned by the function mapper as the element at the index in a new array returned by the operation.
const arr = [1,2,3,4,5]
const doubled = arr.map(x => x * 2) // [2,4,6,8, 10]
A over simplified implementation of map (without the index and originalArray params) might look like this. Let's assume that instead of being a method on the array instance, it's a function that takes an array and a mapper function.
I would not recommend re-implementing in production code, there's the native implementation as well as several libraries such as lodash and underscore that implement it.
function map(arr, mapper) {
const result = [];
for (const item of arr) {
const resultItem = mapper(item);
result.push(resultItem);
}
return result;
}
function double(x) {
return x * 2;
}
const doubled = map([1,2,3,4,5,6], double); // [2, 4, 6, 8 ,10, 12]

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"

Iteratively adding up first and last numbers in an array

I'm trying to write a function that continually adds together the first and last elements of an array using forEach with array.shift() + array.pop().
The problem is that the for-loop doesn't complete the innermost numbers, and so the array is always left with 2 values inside of it.
Code:
function choreAssignment(chores) {
chores.sort(function(a, b) {return a - b});
var assignment = [];
chores.forEach(function() {
assignment.push((chores.pop() + chores.shift()));
});
return assignment.sort(function(a, b) {return a - b});
}
The above code works as expected, but it leaves the innermost two values inside the chores array.
For example if I run:
Code:
var arr = [1, 4, 7, 2, 5, 9, 4, 3];
choreAssignment(arr);
I get:
[8, 9, 10]
Ie, it adds 9 & 1, 7 & 2, 5 & 3, but it leaves [4, 4] inside the array.
I'm not sure why this is. Thank you.
Try changing the forEach to:
while (chores.length) {
assignment.push((chores.pop() + chores.shift()));
}
Note this assumes there are always an even number of elements in array

Categories

Resources