How to increase all the element in an int array by 1?
Ex:
make var a = [1,2,3,4] and increase all elements inside so that the result gives
a = [2,3,4,5]
Is there any method except doing a = a+[1,1,1,1]?
Nowadays it is being done with the arrow functions as following :)
console.log([1,2,3,4].map(v=> v+1));
Sure. Just use the JavaScript map function.
[1,2,3,4].map(function(entry) {
return entry+1;
});
As per MDN docs;
The map() method creates a new array with the results of calling a
provided function on every element in this array.
Another example of the map function in action provided by the MDN I added is;
var numbers = [1, 4, 9];
var doubles = numbers.map(function(num) {
return num * 2;
});
// doubles is now [2, 8, 18]
You can take advantage of the map() function, which will map each item within your array to a function that can be used to transform it:
[1,2,3,4].map(function(item) {
// Increment each item by 1
return item + 1;
});
Example
console.log([1, 2, 3, 4].map(function(item) {
return item + 1;
}));
You can use the map function
var a = [1,2,3,5];
var x = a.map(function(item){
return item+1;
})
console.log(x)
DEMO
Related
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'm trying to understand the Seek and Destroy challenge below.
Task: You will be provided with an initial array (the first argument in the destroyer function), followed by one or more arguments. Remove all elements from the initial array that are of the same value as these arguments.
This is the initial code below:
function destroyer(arr) {
// Remove all the values
return arr;
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
After several (really) several attempts and looking at other people's code, I was able to resolve the task. However, I think it was more out of luck. I’ve copied my code below, but I was hoping someone could clarify a couple of things for me.
The code below passes whether I return val or args within the iterateThroughArray function. Why is that?
If I am supposed to be comparing ALL arguments against the first argument, where in this code am I indicating that? I kept thinking I needed to splice the first argument to compare all other arguments against it or create a variable for argument[0]. Any guidance you can provide is greatly appreciated!
function destroyer(arr) {
var args = Array.from(arguments); //this also converts them to an array
var iterateThroughArr = function (val) {
if (args.indexOf(val) ===-1){
return args;
}
};
return arr.filter(iterateThroughArr);
}
This may sound a lot to take in but here is my explanation
function destroyer(arr) {
var args = Array.from(arguments); //Here arr is converted to [Array(6),2,3]
//console.log(args)
/* var iterateThroughArr = function (val) {
if (args.indexOf(val) ===-1){
return args;
}
};
return arr.filter(iterateThroughArr);
*/
// to make more clear the above code can be rewritten as below
var arr = arr.filter(function (val) {
console.log("args = "+ args + " val = " + val + " indexOf(val) " + args.indexOf(val) )
// here you are itterating through each arr val which in this case is[1,2,3,1,2,3]
// if you dont believe me uncomment the next console.log() and see the output
// console.log(val)
if (args.indexOf(val) ===-1){
// here is where the magic happens
// Now you are checking if val exisists by using a builtin method called .indexOf()
// In general, .indexOf() returns -1 if a value does not exist within an array
//Below is working example
/* var array = [1,2,3,4,5]
console.log(array.indexOf(1)) // 0 since it is located at index 0
console.log(array.indexOf(5)) // 4 since it is located at index 4
console.log(array.indexOf(10)) // -1 since it does not exisit
*/
// Therefore, if value passes the above if statement
//then that means it doesnot exisit on args([Array(6),2,3])
//which as a result will be included on the filtered array
return args;
}
});
return arr;
}
var val = destroyer([1, 2, 3, 1, 2, 3], 2, 3);
//console.log(val)
Basically, what you need to understand is how filter works and how .indexOf works.
For more detail visit Mozilla documentation: .indexOf() and .filter()
Give this a try:
function destroyer(arr) {
// arr1 is equal to the array inside arr
var arr1 = arr.slice(arguments);
// arr2 becomes an array with the arguments 2 & 3
var arr2 = Array.prototype.slice.call(arguments, 1);
// this function compares the two and returns an array with elements not equal to the arguments
return arr1.concat(arr2).filter(function (item) {
return !arr1.includes(item) || !arr2.includes(item)
})
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
I have array elements and I am trying to multiply by 2 only using filter method (not map).The output I am expecting something looks like this [2,4,6,8,10].Here is my code
var array = [1,2,3,4,5];
array.filter( val => val * 2);
Not filter , you should use map function in this case.
var array = [1,2,3,4,5];
array = array.map(function(val){return val*2;});
console.log(array);
Demo
By using only the filter method... you could try using it as like an iterator (note that this is NOT how filter is supposed to be used):
var array = [1,2,3,4,5];
array.filter( function (val, i, array) { array[i] = val * 2; });
//array now has [2,4,6,8,10]
This is ugly, but this is what you would do if you can only use filter
Try using this
var new_array = array.map(function(e) {
e = e*2;
return e;
});
First of all you need to understand the functions of map, filter, and reduce.
From your requirement it should be function of map but you want with filter which is not obvious.
Map:
When you call map on an array, it executes that callback on every
element within it, returning a new array with all of the values
that the callback returned.
Filter
filter executes that callback on each element of the array, and spits
out a new array containing only the elements for which the callback returned true.
let items = ['1','2','3','4','5'];
let numbers = items.map(item=>item*2);
console.log(items);
console.log(numbers);
If you really want to use filter() you could to that:
Array.prototype.filter = Array.prototype.map
var array = [1,2,3,4,5];
array.filter( val => val * 2);
But please don't.
var numList = [1, 2, 3, 4, 5, 6, 7,8 ];
var doubleUp = (array) => array.map(item=>item*2);
console.log(doubleUp(numList));
//returns
[
2, 4, 6, 8,
10, 12, 14, 16
]
so here is my code (not working) what I want to do is loop through the hashmap and return a new hashmap with squared number so that any hashmap goes into function pow as an argument. and I want to do it in ES6 way.
var numbers = {};
numbers['two'] = [2, 4, 9];
numbers['one'] = [1, 2, 3];
function pow(arr){
for (var x in arr){
x.map(function(value)){
return value*value;
}
}
}
pow(numbers);
As Rocket commented above, when using a for...in loop, x is the index, not the actual value. You'll need to use arr[x] instead of simply x in your loop.
You can use arr.forEach() to iterate through an array's values in a more intuitive way, but there are compatibility considerations with that method, so your ability to use it may depend on where you're running the code. (More information here.) However, in this case, as Lucas pointed out in the comments, you're passing in an object, not an array, so forEach() will not work.
This does what you are looking for...as previously stated x in the for loop is the index. You would use arr[x] to get the array such as numbers['one']. You have to redefine the arr[x] with the new map you return. This does the trick. In ES6 you could destructure and then loop through. Feel free to ask for that if you'd like.
function pow(hm) {
for (var x in arr) {
hm[x] = hm[x].map(function(value) {
return value*value;
});
}
return hm;
}
ok I solved it `
var numbers = {};
numbers['one'] = [2, 4, 9];
numbers['two'] = [1, 6, 8];
function pow(arr) {
var arr1 = arr.map(function(value) {
return value*value;
});
return arr1;
}
console.log(pow(numbers['two']));
pow(numbers['two']);
` this is what I want - it's here http://jsbin.com/bicamimifi/edit?js,console,output
Let's say I'm given an array. The length of this array is 3, and has 3 elements:
var array = ['1','2','3'];
Eventually I will need to check if this array is equal to an array with the same elements, but just twice now. My new array is:
var newArray = ['1','2','3','1','2','3'];
I know I can use array.splice() to duplicate an array, but how can I duplicate it an unknown amount of times? Basically what I want is something that would have the effect of
var dupeArray = array*2;
const duplicateArr = (arr, times) =>
Array(times)
.fill([...arr])
.reduce((a, b) => a.concat(b));
This should work. It creates a new array with a size of how many times you want to duplicate it. It fills it with copies of the array. Then it uses reduce to join all the arrays into a single array.
The simplest solution is often the best one:
function replicate(arr, times) {
var al = arr.length,
rl = al*times,
res = new Array(rl);
for (var i=0; i<rl; i++)
res[i] = arr[i % al];
return res;
}
(or use nested loops such as #UsamaNorman).
However, if you want to be clever, you also can repeatedly concat the array to itself:
function replicate(arr, times) {
for (var parts = []; times > 0; times >>= 1) {
if (times & 1)
parts.push(arr);
arr = arr.concat(arr);
}
return Array.prototype.concat.apply([], parts);
}
Basic but worked for me.
var num = 2;
while(num>0){
array = array.concat(array);
num--}
Here's a fairly concise, non-recursive way of replicating an array an arbitrary number of times:
function replicateArray(array, n) {
// Create an array of size "n" with undefined values
var arrays = Array.apply(null, new Array(n));
// Replace each "undefined" with our array, resulting in an array of n copies of our array
arrays = arrays.map(function() { return array });
// Flatten our array of arrays
return [].concat.apply([], arrays);
}
console.log(replicateArray([1,2,3],4)); // output: [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
What's going on?
The first two lines use apply and map to create an array of "n" copies of your array.
The last line uses apply to flatten our recently generated array of arrays.
Seriously though, what's going on?
If you haven't used apply or map, the code might be confusing.
The first piece of magic sauce here is the use of apply() which makes it possible to either pass an array to a function as though it were a parameter list.
Apply uses three pieces of information: x.apply(y,z)
x is the function being called
y is the object that the function is being called on (if null, it uses global)
z is the parameter list
Put in terms of code, it translates to: y.x(z[0], z[1], z[2],...)
For example
var arrays = Array.apply(null, new Array(n));
is the same as writing
var arrays = Array(undefined,undefined,undefined,... /*Repeat N Times*/);
The second piece of magic is the use of map() which calls a function for each element of an array and creates a list of return values.
This uses two pieces of information: x.map(y)
x is an array
y is a function to be invoked on each element of the array
For example
var returnArray = [1,2,3].map(function(x) {return x + 1;});
would create the array [2,3,4]
In our case we passed in a function which always returns a static value (the array we want to duplicate) which means the result of this map is a list of n copies of our array.
You can do:
var array = ['1','2','3'];
function nplicate(times, array){
//Times = 2, then concat 1 time to duplicate. Times = 3, then concat 2 times for duplicate. Etc.
times = times -1;
var result = array;
while(times > 0){
result = result.concat(array);
times--;
}
return result;
}
console.log(nplicate(2,array));
You concat the same array n times.
Use concat function and some logic: http://www.w3schools.com/jsref/jsref_concat_array.asp
Keep it short and sweet
function repeat(a, n, r) {
return !n ? r : repeat(a, --n, (r||[]).concat(a));
}
console.log(repeat([1,2,3], 4)); // [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
http://jsfiddle.net/fLo3uubk/
if you are inside a loop you can verify the current loop index with the array length and then multiply it's content.
let arr = [1, 2, 3];
if(currentIndex > arr.length){
//if your using a loop, make sure to keep arr at a level that it won't reset each loop
arr.push(...arr);
}
Full Example:
https://jsfiddle.net/5k28yq0L/
I think you will have to write your own function, try this:
function dupArray(var n,var arr){
var newArr=[];
for(var j=0;j<n;j++)
for(var i=0;i<arr.length;i++){
newArr.push(arr[i]);
}
return newArr;
}
A rather crude solution for checking that it duplicates...
You could check for a variation of the length using modulus:
Then if it might be, loop over the contents and compare each value until done. If at any point it doesn't match before ending, then it either didn't repeat or stopped repeating before the end.
if (array2.length % array1.length == 0){
// It might be a dupe
for (var i in array2){
if (i != array1[array2.length % indexOf(i)]) { // Not Repeating }
}
}