Let say I have an array:-
var arr = [0,1,2,3,4]
I need to pass only "1" and "4" to function below
function func1(onlyArray){
//Do Stuff...
}
I have tried both but both also dont work
func1(arr[1,4])
func1(arr[[1],[4]])
Can anyone show me the right way or give me some keyword?
You can use this:
func([arr[1], arr[4]])
We are taking the elements at index 1 and 4 of the array arr and creating a new array with those elements. Then we pass that newly created array to func.
If you need a single array instead of 2, use this:
var arr = [0,1,2,3,4];
function func1(onlyArray){
//Do Stuff...
console.log(onlyArray); // [1, 4]
}
func1(arr.filter((item,index) => index === 1 || index === 4));
So using your array:
var arr = [0,1,2,3,4];
and your function:
function myFunction(newArr){
//Do stuff
console.log(newArr);
};
You can wrap the array indexes you want to use inside of their own array when you call the function, like the following:
myFunction([arr[1], arr[4]]); //Output is [1, 4]
Related
Write a function called push which accepts two parameters, an array and any value.
The function should add the value to the end of the array and then return the new length of the array.
Do not use the built in Array.push() function!
Examples:
var arr = [1, 2, 3];
push(arr, 10); // 4
arr; // [1, 2, 3, 10]
My question is How to return a new array with the new length.
You can try this out . Get the length of the existing array and put the new number at arr[length] index of it . See the code below:
function push(arr,num){
var length = arr.length;
arr[length]=num;
return arr;
}
you could do it with something like this:
const push = (a, v) => (a[a.length] = v,a);
array = [1,2,3]
console.log(push(array, 4));
This question already has answers here:
Does JavaScript pass by reference? [duplicate]
(13 answers)
Closed 3 years ago.
Since arrays are passed to functions by reference, when I set the array to be equal to something else inside a function, and try to log it outside of the function again, why does the value remain the same even though I modified it in the function?
let arr = [1, 2];
console.log(arr); // Logs [1, 2]
add(arr, 3)
console.log(arr); // Logs [1, 2] again
function add(array, el)
{
array = [el];
console.log(array); // Logs [3]
}
Why does the console.log after calling add log out [1, 2] instead of [3] (which is the value of the el parameter)?
You aren't modifying the array.
You're changing the value of the array variable (from a reference to the old array to a reference to a new array).
For comparison, if you were to modify the existing array:
let arr = [1, 2];
console.log(arr);
add(arr, 3)
console.log(arr);
function add(array, el) {
array.length = 0;
array.push(el);
console.log(array);
}
You're confusing the scope of the array.
When you pass in an array to the function and set that variable equal to something else like so;
function add(array, el)
{
array = [el];
}
You're just setting the variable equal to something else and you're not modifying the array. If you want to modify the array you would do something like:
function add(array, el)
{
array[0]=el; // changing the first element to 3
}
Now you will see the array is updated with the first element to 3. This is how it works with updating the array.
If you want the array to be an entirely new array you would do something like:
arr = add(arr, 3);
function add(array, el)
{
array = [el];
return array;
}
As I'm learning the forEach() method in JavaScript, I have several questions related to it.
Currently I've written the following piece of code:
var arr = [1,2,3,4,5,6];
arr.forEach(function(elem, idx, arr){
elem=elem*2;
});
alert(arr); // "1,2,3,4,5,6"
My goal is to simply multiply each element in arr by 2, however when I use alert to examine the final values it seems that values inside arr hasn't been modified. What's the problem here?
Also I'm a little confused about the 3 arguments that forEach's function takes. First, is it required to pass in 3 arguments? What will happen if one doesn't provide exactly 3 arguments? Some tutorials I've looked at seem to provide only 1 argument, yet the explanation wasn't clear. Second, do the names of arguments matter (e.g. e, elem, or element)?
Thank you.
Your approach
You are not assigning new value to anything else but the elem, which is only in callback's scope. Modify your code, so that the elem * 2 is assigned to arr[idx]. Working example:
var arr = [1, 2, 3, 4, 5, 6];
arr.forEach(function(elem, idx) {
arr[idx] = elem * 2;
});
document.body.textContent = arr;
Better approach
For tasks like that however, you should use map:
var arr = [1, 2, 3, 4, 5, 6];
arr = arr.map(function(num) {
return num * 2;
});
document.body.textContent = arr;
The array is not getting modified cus you are not modifying it. To do that update the code as following.
var arr = [1,2,3,4,5,6];
arr.forEach(function(elem, idx, arr){
arr[idx] = elem*2
});
console.log(arr);
If you check the console you would see the updated arr.
you cannot edit the array in place by returning the new value or changing elem. You can however use the idx variable like arr[idx] = elem * 3 or use the map function.
you can omit the parameters that you don't need
you can name them whatever you want
For first problem, just use map
var arr = [1,2,3,4,5,6];
arr = arr.map(function(elem){
return elem*2;
});
alert(arr); // "2,4,6,8,10,12"
arguments is optional, and names doesn't matter at all.
The arguments are optional.
idx lets you know the index of the array element you are currently evaluating.
arr, is the array you are evaluating.
so elem == arr[idx]
For the life of me, I just can't figure out what I'm doing wrong here.
I'm trying to use both the reduce and concat array methods to take all of the values of a 2d array and combine them into a single value (basically condense them into a single array and then sum them up).
The problem that I keep running into is that when I try to make a for/loop to concat each array element, the argument that I'm passing into the function is not being recognized as an array, thus my call to .concat() is failing. I've placed a console.log() at the beginning of the function to see if the element is being recognized as the first array element in the 2d array, and it's coming up as "1"(?).
I tried another test outside of the function, and it logs as the actual array element. What am I doing wrong here? code below:
var arrays = [[1, 2, 3], [4, 5], [6]];
var myArray = arrays[0]; // Test
console.log(myArray); // Test
var flatArray = arrays.reduce(function(arrays)
{
console.log(arrays[0]); // Test
for (var i = 0; i < arrays.length - 1; i++)
{
arrays[0].concat(arrays[i+1]);
}
return arrays;
});
console.log(flatArray);
This is the output that I keep getting:
Array [ 1, 2, 3 ]
1
TypeError: arrays[0].concat is not a function
It's almost seems like array is being converted to a number-type when inside the function...?
You have an error in your code here:
var flatArray = arrays.reduce(function(param) {})
that param will be an element of your arrays vector.
Check this https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
You are using .reduce() incorrectly and you don't even need to use it to flatten an array. You can just do this:
var flatArray = [].concat.apply([],arrays);
Working demo: http://jsfiddle.net/jfriend00/wfjyfp42/
To understand .reduce(), the callback you pass it gets four arguments (see MDN reference). The first two arguments are important in using .reduce() correctly:
callback(previousValue, currentValue, index, array)
The previousValue is the accumulated value so far in the reduction. The currentValue is the next element of the array that is being iterated. The last two arguments do not need to be used if not needed.
Your code is only using the previousValue so it is never looking at the next item in the array as passed in by .reduce().
You could make a solution work using .reduce() like this:
var flatArray = arrays.reduce(function(previousValue, currentValue) {
return previousValue.concat(currentValue);
}, []);
Working demo: http://jsfiddle.net/jfriend00/2doohfc5/
Reduce performs an operation on two elements.
var sum = [[1, 2, 3], [4, 5], [6]].reduce(function(a, b) {
return a.concat(b);
}).reduce(function(a, b) {
return a + b;
});
I have an array and I want to put it in another array using indexes.
For example:
arry[1].push(sub_array_1)
array[2].push (sub_array_2)
But I get an error if I write:
var sub_array_1 = [1, 2, 2, 2, 2];
arry[1].push(sub_array_1)
Using spread operator
var subArray = [1, 4, 6, 7];
var mainArray = [6, 7, 8];
var index = 1;
mainArray = [...mainArray.slice(0, index), subArray, ...mainArray.slice(index)];
Assuming:
var arry = [9,8,7];
var sub_array_1 = [1,2,2,2,2];
If you are trying to insert sub_array_1 into arry, as a single element, just use splice directly:
arry.splice(1, 0, sub_array_1);
The result will be:
[9,[1,2,2,2,2],8,7]
On the other hand, if you are trying to insert the contents of sub_array_1 before the second element of arry, you can do something like this:
Array.prototype.splice.apply(arry, [1, 0].concat(sub_array_1));
The result will be:
[9,1,2,2,2,2,8,7]
Here is a more general function:
function insert(arrayDest, index, arraySrc) {
Array.prototype.splice.apply(arrayDest, [index, 0].concat(arraySrc));
}
[EDITED]
Starting with ES6, you can simplify the above code using the spread operator (...). For example:
function insert(arrayDest, index, arraySrc) {
arrayDest.splice(index, 0, ...arraySrc);
}
You're using wrong syntax! Follow the either below mentioned approach.
var sub_array_1 = [1,2,2,2,2];
arry[1] = sub_array_1;
// OR
var sub_array_1 = [1,2,2,2,2];
arry.push(sub_array_1);
.push(ele) will add an item to an array, thereby incrementing the length of array by 1. Remember array index starts at 0.
If you need to add an item(array/object/other) to a particular index, use [index]. Eg: arry[0] = [1,23]; arry[1] = [4,5,6,7];
obj.arrayOne.push(arrayLetters);
or
obj['arrayOne'].push(arrayLetters);
let array = []
array.push({"index": 0, "value":100})
console.log(array)
maybe it helping for you