var nums = [1,2,3,5,6,3];
nums = nums.join('')
// I want to replace all occurrences of 3 in nums with an empty string.
// this code works
nums.slice(0).replace(/3/g,''); => [1,2,5,6];
// this code doesn't work, because I replaced 3 with a variable
nums.slice(0).replace(/nums[2]/g, ''); => [1,2,3,5,6,3];
whenever I use an actual character, it works but when I replace it with a variable like (nums[2]), it doesn't work and just returns the same array. is there something I'm missing?
I will shorten up your code a little bit so it doesn't cause too much confusion to you.
Also, you can avoid the slice method since strings by default are immutable and what that means is that every time you execute the replace method or any other string method it will return a brand new string.
var numbersArray = [1, 2, 3, 5, 6, 3];
var numbersString = numbersArray.join(''); // => '1235653'
var numbersWithoutThrees = numbersString.replace(/3/g, ''); // => '1256'
Great so far! The replace method accepts as an argument a RegExp or a string.
For example: numbersString.replace(/3/g, ''); we're using the /3/g RegExp that means find all the '3' occurrences due to the g flag, since there is a '3' is going to be replace for the empty string'' defined in the second parameter in the repace.
But what about the /numbersString[2]/g? Let's check it out:
var result = numbersString.replace(/numbersString[2]/g, ''); // => '123563'
It seems is not replacing anything and that's because there's no 'numbersString[2]' string inside '123563'.
If we want to replace the third element (numberSring[2]) you can do it by replacing the element in that position in the numbersArray and generating a new string by using join once again.
numbersArray[2] = ''; // => [1, 2, "", 5, 6, 3]
numbersString = numbersArray.join(''); // => '12563'
And there it's the result you now don't have that third element on your numbersString variable.
I hope that helps!
Related
I need to [1, 2, 3] over to ['123'].
I must return [1, 2, 3] over to ['123'] while using an arrow function (no regex):
Must be used:
const functionOne = (arrayOne) => {
};
console.log(functionOne([1, 2, 3]));
So, I tried the following:
First, I created a string. This gave me 1,2,3
Then, I removed the commas, so, I could join the numbers. This gave me 123.
Finally, I tried to put back the number as a string into the array but this didn't work. This gave me ['1', '2', '3'] instead of ['123']. I think the .split method is what is wrong in my code but I cannot find another one (currently learning JavaScript).
const functionOne = (arrayOne) => {
let stepOne = arrayOne.toString(arrayOne => arrayOne.toString());
console.log(stepOne);
stepOne = stepOne.split(',').join('');
console.log(stepOne);
return stepOne.split('');
};
console.log(functionOne([1, 2, 3]));
You can join using "" as the delimiter (it will automatically convert the elements to strings as it produces the output string), then put the result in an array as its only element ([____]):
const functionOne = (array) => [array.join("")];
console.log(functionOne([1, 2, 3]));
Issues with your original approach:
Array's toString completesly ignores the argument you're giving it, instead using its default behavior of join(",").
Splitting it on , again just gives you back an array, but this time of strings.
Rejoining that with join('') does give you "123", but doesn't put it in an array.
You could take a recursive function.
const
fn = ([v, ...rest]) => rest.length
? [v + fn(rest)]
: [v];
console.log(fn([1, 2, 3]));
const functionOne = (arrayOne) => {
let stepOne = arrayOne.toString();
stepOne = stepOne.split(',').join('');
return [stepOne];
};
console.log(functionOne([1, 2, 3]));
The .toString() method will convert the array [1, 2, 3] to the string "1,2,3", then .split(',').join('') removes the commas and joins the numbers as a single string "123". Finally, return [stepOne]; returns the string "123" inside an array ['123'].
I am supposed to rotate an array of integers clockwise in JS.
Here is my code for it:
function rotateArray(N, NArray)
{
//write your Logic here:
for(j=0;j<2;j++){
var temp=NArray[N-1];
for(i=0;i<N-1;i++){
NArray[i+1]=NArray[i];
}
NArray[0]=temp;
}
return NArray;
}
// INPUT [uncomment & modify if required]
var N = gets();
var NArray = new Array(N);
var temp = gets();
NArray = temp.split(' ').map(function(item) { return parseInt(item, 10);});
// OUTPUT [uncomment & modify if required]
console.log(rotateArray(N, NArray));
The code accepts an integer N which is the length of the array. The input is as follows:
4
1 2 3 4
The correct answer for this case is supposed to be
4 1 2 3
But my code returns
4 1 1 1
I cannot find where my code is going wrong. Please help me out.
All you need to do is move one item from the end of the array to the beginning. This is very simple to accomplish with .pop() (removes an item from the end of an array), then declare a new array with that element as the first:
function rotateArray(N, NArray) {
const lastItem = NArray.pop();
return [lastItem, ...NArray];
}
console.log(rotateArray(1, [1, 2, 3, 4]));
Doing anything else, like using nested loops, will make things more unnecessarily complicated (and buggy) than they need to be.
If you don't want to use spread syntax, you can use concat instead, to join the lastItem with the NArray:
function rotateArray(N, NArray) {
const lastItem = NArray.pop();
return [lastItem].concat(NArray);
}
console.log(rotateArray(1, [1, 2, 3, 4]));
If you aren't allowed to use .pop, then look up the last element of the array by accessing the array's [length - 1] property, and take all elements before the last element with .slice (which creates a sub portion of the array from two indicies - here, from indicies 0 to the next-to-last element):
function rotateArray(N, NArray) {
const lastItem = NArray[NArray.length - 1];
const firstItems = NArray.slice(0, NArray.length - 1);
return [lastItem].concat(firstItems);
}
console.log(rotateArray(1, [1, 2, 3, 4]));
function rotate(array,n){
Math.abs(n)>array.length?n=n%array.length:n;
if(n<0){
n=Math.abs(n)
return array.slice(n,array.length).concat(array.slice(0,n));
}else{
return array.slice(n-1,array.length).concat(array.slice(0,n-1));
}
}
console.log(rotate([1, 2, 3, 4, 5],-3));
The answer by #CertainPerformance is great but there's a simpler way to achieve this. Just combine pop with unshift.
let a = [1,2,3,4];
a?.length && a.unshift(a.pop());
console.log(a);
You need to check the length first so you don't end up with [undefined] if you start with an empty array.
I am trying to create this memory game in ReactJS and I have made an array in which I add 4 random numbers. Now everytime I press play game I need to fill the array with 4 random numbers 0 to 3 but I keep getting random commas that come out of nowhere in the array. I am quite new to React so any help is appreciated.
I have tried different methods of filling up the array but the commas still appear. P.S: keepArray was initialized just before the for loop.
for (let i = 0; i < 4; i++) {
let rand = Math.floor(Math.random() * 4)
keepArray = [...keepArray + rand]
console.log(keepArray)
}
Solution:
Replace:
keepArray = [...keepArray + rand]
with:
keepArray = [...keepArray, rand]
Explanation:
The spread operator (...) is literally "spreading" your array, that's why you need commas. The example bellow may help to visualize it:
// Let's start with a simple array:
var myArray = [1, 2, 3];
// Now, we add another element to it using spread:
var updatedArray = [...myArray, 4];
// Here, ...myArray is translated to [1, 2, 3]
// That means that the above could be read as:
var updatedArray = [1, 2, 3, 4];
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
For an extra explanation about the "+" behavior, see Pavan Bahuguni answer.
The above answer does fix the problem, but the real reason for the behaviour is as follows.
The + operator is overloaded to serve the purposes of both number addition and string concatenation. When + receives an object (including array in your case) for either operand, it first calls the ToPrimitive abstract operation on the value, which then calls the [[DefaultValue]] algorithm with a context hint of number. Which intern calls toString method on the array.
var val = [1,2,3] + 1;
console.log(val); // "1,2,31"
And then you are trying to spread that string in an array like so,
var arr = [...val];
console.log(arr); // ["1", ",", "2", ",", "3", "1"]
this is the actual reason why you are seeing those commas.
Hello I have the following:
var a = [1, 2, 3]
I would like to update this array to:
a = [11,22,33]
I am trying to do something like
a.map(repeat(2));
but it results in an error.
I know I could easily loop through this, but I am trying to practice using more concise code, and expand my knowledge a bit on different functions, and how to use them.
Is something like this possible?
You could convert the number to string, repeat the value and convert it back to number.
var a = [1, 2, 3]
a = a.map(a => +a.toString().repeat(2));
console.log(a);
Given that you seem to be looking for repeating the digits, use strings for that. Which have a handy repeat method for this purpose:
a.map(x => Number(String(x).repeat(2))));
If you want to use your notation, you need to make a higher-order repeat function that returns another function to be used as the map callback:
function repeat(times) {
return x => String(x).repeat(times);
}
a.map(repeat(2)).map(Number)
Yes that is possible. You can define repeat as a function that returns a function:
function repeat(times) {
return function (value) {
return +String(value).repeat(times);
}
}
// Your code:
var a = [1, 2, 3];
var result = a.map(repeat(2));
console.log(result);
The map method expects a function as argument, so the call to repeat(2) should return a function. That (inner) function uses String#repeat after converting the value to string, and then converts the result back to number with the unary +.
Here you go, number version and string version
const doubleIt = n => Number(`${n}${n}`);
const arr = [1, 2, 3, 55];
const strArr = arr.map(o => `${o}${o}`);
const numArr = arr.map(o => o * 11);
const numFromStringsArr = arr.map(o => doubleIt(o));
console.log(strArr);
console.log(numArr);
console.log(numFromStringsArr);
You can create an array of N .length with Array(), use Array.prototype.fill() to fill the created array with current element of .map() callback, chain Array.prototype.join() with "" as parameter, use + operator to convert string to number
var a = [1, 2, 3], n = 2;
a = a.map(el => +Array(n).fill(el).join(""));
console.log(a);
Simply, try it with Array join() method:
a.map(x => Array(2).join(x));
I have an array and simply want to get the element at index 1.
var myValues = new Array();
var valueAtIndex1 = myValues.getValue(1); // (something like this)
How can I get the value at the 1st index of my array in JavaScript?
You can access an element at a specific index using the bracket notation accessor.
var valueAtIndex1 = myValues[1];
On newer browsers/JavaScript engines (see browser compatibility here), you can also use the .at() method on arrays.
var valueAtIndex1 = myValues.at(1);
On positive indexes, both methods work the same (the first one being more common). Array.prototype.at() however allows you to access elements starting from the end of the array by passing a negative number. Passing -1 will give the last element of the array, passing -2 the second last, etc.
See more details at the MDN documentation.
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1].
See Accessing array elements for more info.
You can just use []:
var valueAtIndex1 = myValues[1];
indexer (array[index]) is the most frequent use. An alternative is at array method:
const cart = ['apple', 'banana', 'pear'];
cart.at(0) // 'apple'
cart.at(2) // 'pear'
If you come from another programming language, maybe it looks more familiar.
shift can be used in places where you want to get the first element (index=0) of an array and chain with other array methods.
example:
const comps = [{}, {}, {}]
const specComp = comps
.map(fn1)
.filter(fn2)
.shift()
Remember shift mutates the array, which is very different from accessing via an indexer.
Update 2022
With ES2022 you can use Array.prototype.at():
const myValues = [1, 2, 3]
myValues.at(1) // 2
at() also supports negative index, which returns an element from the end of the array:
const myValues = [1, 2, 3]
myValues.at(-1) // 3
myValues.at(-2) // 2
Read more:
MDN, JavascriptTutorial, Specifications
You can use [];
var indexValue = Index[1];
As you specifically want to get the element at index 1. You can also achieve this by using Array destructuring from ES6.
const arr = [1, 2, 3, 4];
const [zeroIndex, firstIndex, ...remaining] = arr;
console.log(firstIndex); // 2
Or, As per ES2022. You can also use Array.at()
const arr = [1, 2, 3, 4];
console.log(arr.at(1)); // 2