Javascript array in function - javascript

My little problem is that when I call function go. I want when logic = true return array and when logic = false, so I need delete all elements in this array, but this solution doesn´t work.
function go(logic) {
if (logic)
{
return array;
array = [];
}
else
{
array = [];
}
$("#ok").click(function(){array.push(1);});
$("#close").click(function(){array.push(2);});
var array = [];
}

I think you want this instead:
function go(array, logic){
return logic ? array : [];
}
This uses the conditional operator. The function will return the original array if your condition is satisfied, otherwise, it returns an empty array.
You can then use it to reset an array like this:
array = go(array, logic);

The code after the return won't be executed.
Guess you're using a global var? But I don't understand why you set the array var at the end of the function...
function go(logic) {
if (logic) {
var tmp = array;
array = [];
return tmp;
} else {
array = [];
}
}

If i got this right you need to do it like this:
function go(logic){
//if logic is false clear array
if(!logic){
x = [];
}
//return the array
//now empty if !logic
return x;
}
//create array
var x = [];
//push values on click
$('.elem').click(function(){x.push('someval');});

Related

How do I update a variable inputted to a function?

I am trying to make a function in my js file that will remove an item from an array and then save the new array to the variable. But here's the thing: I don't want it to only save ONE variable, I want it to save any array variable that I input. What I mean is something like this:
const list = [1,2,3];
function removeItem(array,index)
{
let newArray = [];
for(var i = 0 ; i < array.length ; i++)
{
if(i != index)
{
newArray.push(array[i]);
}
}
array = newArray; // where it saves the variable
}
removeItem(list,0);
You can create a prototype function, see this
Array.prototype.removeItem = function(what) {
if (this.indexOf(what) >= 0) this.splice(this.indexOf(what), 1);
}
var foo = [1, 2, 3];
foo.removeItem(2);
console.log(foo);
You just want arr.splice(i, 1);
The simplest way is probably to return the new array and let the calling code decide where to save it:
function removeItem(array, index) {
let newArray = [];
for(var i = 0 ; i < array.length ; i++) {
if(i != index) {
newArray.push(array[i]);
}
}
return newArray;
}
And:
list = removeItem(list, 0);
This is probably ideal because modifying objects passed to a function as arguments is generally unexpected. It's more common to return the new value.
If you want to modify the array in place then you'd need to only make edits to the array reference directly in the function and not use any kind of newArray copy. Which could be as simple as:
function removeItem(array, index) {
array.splice(index, 1);
}
And:
removeItem(list, 0);
But this could be very unintuitive since list is an argument to the function and you're not calling anything on list itself. Contrast that to the syntax used in splice which is called on the array itself and implies that it may modify that array:
list.splice(0, 1);
(Though some array methods in JavaScript return a new array while others modify the array in place. It's always best to refer to the documentation to make sure.)

Javascript how do i get my function array to give me more then the first value

function countUniqueItems(arr) {
nums = [];
for (i = 0; i < arguments.length; i++) {
const item = arr[i];
console.log(i);
//console.log(item);
if (nums.includes(arr) === true) {
//console.log('8 is in the array');
//nums.push(arr)
} else {
nums.push(arr);
//console.log('8 is NOT in the array');
//nums.push(item)
}
}
return nums;
}
countUniqueItems(1, 2);
So it will give back the first argument which is 1 but i want it to be able to say argument 2 and 3 and so on
So you need to pass an array into the function, in place of 1,2 pass [1,2].
Then inside your function, you should use arr.length in place of arguments.length.
Then you look at your logic for the loop, you are pushing atm arr into nums, but if you pass and array that isn't really want you want, you should be pushing item as that is the variable which represents your current element from the array.
It looks from you comments like you're trying to make a unique list of inputs. Perhaps something like this would do the trick.
EDIT: Updated to use arguments
function uniqueNumbers() {
let arrayOfArguments = [...arguments]
let uniqueNums = [];
arrayOfArguments.map(i => !uniqueNums.includes(i) ? uniqueNums.push(i) : null);
return uniqueNums;
};
console.log(uniqueNumbers(1,2,3,3));
you should either pass an array to countUniqueItems or use the arguments keyword in the for-loop.
Your code is only seeing 1 (as arr inside the function).
basic implementation to find unique items
function countUniqueItems(...arr) {
let nums = [];
for (let num of arr) {
if (nums.indexOf(num) === -1) nums.push(num);
}
return nums;
}
console.log(countUniqueItems(1, 2, 1));
Using Set you can remove the duplicate values, you dont need to do logic run the loop to find the unique values from array.
const a = [1,2,3,3];
const uniqueSet = new Set(a);
uniqueSet.size
let uniqueFinder = arr => { const uniqueSet = new Set(arr); return uniqueSet.size}
const arrywithduplicates = [1,2,3,3,4,4];
uniqueFinder(arrywithduplicates) // return 4
Read more about Set : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

How is my array that I am not using getting updated?

Here is my function:
function RemoveOutputKeys(array){
var temp = array;
for(var object in temp){
delete temp[object]['statusCode']
delete temp[object]['statusResponse']
}
console.log(array)
if(temp == array)
console.log("how is this possible?!?!!?!?!")
return temp
}
and here is the input I am providing,
array = [{'statusCode':400},{'statusCode':200}]
It makes sense for temp to get updated but I don't want the array to get updated. How can i fix this issue?
Thanks
Use Array.prototype.filter() instead of for in
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
function RemoveOutputKeys(array) {
return array.filter(function(myArray) {
if (!myArray['statusCode'] && !myArray['statusResponse']) {
return myArray;
}
});
}
var originalArray = [{'statusCode':400}, {'statusCode':200}, {'test': 'test'}];
var tempArray = RemoveOutputKeys(originalArray);
console.log(originalArray, tempArray);
https://jsfiddle.net/3kbypvcs/2/
If you want create new array instead of alias/reference use:
var newArray = oldArray.slice();

Student trying to understand callback functions

Hi I'm trying to learn how to implement callback functions. My teacher has helped me out multiple times but I still can't pass data through the following equation below. I'm trying to get certain elements of array to get pushed into a new function if only they pass a test within the function. Please have a look and thank you for your input. An explanation as to why I get an empty array and resources to further my understanding would be appreciated.
// EACH DEFINITION
function each (collection, callback) {
for(var i = 0; i < collection.length; i ++){
callback(collection[i]);
}
}
// VARIABLE DECLARATION
var myArray = [1,2,3,4,5,6];
var isEven = function (num) {
return num % 2 === 0;
};
// IMPLEMENT DEFINITION
function implement(array, test){ // array = myArray, test = isEven
var arr = [];
each(array, function(item){
test(item);
});
if(test(array)){
arr.push(array);
}
return arr;
}
// IMPLEMENT INVOCATION
implement(myArray, isEven);
You are building arr outside the each() loop.
I would think your code would be like this:
// IMPLEMENT DEFINITION
function implement(array, test){ // array = myArray, test = isEven
var arr = [];
each(array, function(item){
if(test(item)) {
arr.push(item);
}
});
return arr;
}
Though in this case there is no reason for your implement() filtering function at all, since javascript Array prototype already has a filter method. You could simplify your call to this:
var filteredArray = myArray.filter(isEven);
Though you might also then want to change your isEven definition to be more correct as:
var isEven = function (num, index, array) {
In your case you don't need to work with the last two parameters.
// EACH DEFINITION
function each (collection, callback, results) {
for(var i = 0; i < collection.length; i ++){
callback(collection[i]);
}
console.log(results);
}
// VARIABLE DECLARATION
var myArray = [1,2,3,4,5,6];
var isEven = function (num, array) {
return num % 2 === 0;
};
// IMPLEMENT DEFINITION
function implement(array, test){ // array = myArray, test = isEven
var arr = [];
function filter (item) {
if (test(item)) {
arr.push(item);
}
}
each(array, filter, arr);
// If you return arr here, it will still be empty. You must pass it to functions it is being operated on.
}
// IMPLEMENT INVOCATION
implement(myArray, isEven);
Not only are you trying to push to arr outside of your loop, but you're trying to return arr before it has gained any values.
Two points:
First, your implementation of callback functions is correct. As far as the concept of callbacks goes, you are calling and passing the functions correctly.
However, your implement() function probably has a bug. You are not pushing to arr until after each() has already been called:
function implement(array, test) { // array = myArray, test = isEven
var arr = [];
each(array, function(item) {
result = test(item);
});
// This block should be in the loop itself
// It should also refer to item, not array
if (test(array)) {
arr.push(array);
}
return arr;
}
Try this fix based on the code you provided:
// EACH DEFINITION
function each(collection, callback) {
for (var i = 0; i < collection.length; i++) {
callback(collection[i]);
}
}
// VARIABLE DECLARATION
var myArray = [1, 2, 3, 4, 5, 6];
var isEven = function(num) {
return num % 2 === 0;
};
// IMPLEMENT DEFINITION
function implement(array, test) { // array = myArray, test = isEven
var arr = [];
each(array, function(item) {
if (test(item)) {
arr.push(item)
}
});
if (test(array)) {
arr.push(array);
}
return arr;
}
// IMPLEMENT INVOCATION
var result = implement(myArray, isEven);
console.log(result); // For snippet results
Your callback, as you defined it, is
function(item){
test(item);
}
this will only call test on each item and that's it. Since you want to take it further and add item to arr if test returns true, you should put that checking code inside the callback as well, making it
function(item){
if (test(item)) {
arr.push(item);
}
}
so that this function will be called for each of the item.
Also, this part
if(test(array)){
arr.push(array);
}
is incorrect because you are passing a whole array into isEven when isEven is expecting a number. test(array) will always return false; that's why your arr is empty.
Modifying your code to work as you wanted, it would be
// IMPLEMENT DEFINITION
function implement(array, test){ // array = myArray, test = isEven
var arr = [];
each(array, function(item){
if (test(item)) {
arr.push(item);
}
});
return arr;
}
Resources wise, there are callbacks tutorial widely available online, as well as best practices. You can easily find one that suits you best by googling.
It looks to me like the entire issue here is in the implementation section you denote. All of the other code looks adequate.
each(array, function(item){
test(item);
});
Alright, first let's examine this piece of code. You are making a call to your each function, which will use the callback anonymous function defined here as shown.
However, if you were to look at the each function itself, there is no return (which means it returns undefined by default). There is also no modification being done in each. As a result, this set of code has no effect on the execution of the code, and from certain advanced compilation technique may actually be removed by the V8 engine in chrome if that was being used.
This means the only aspect of your code which is executing is
var arr = [];
if(test(array)){
arr.push(array);
}
return arr;
At this point, test is still the isEven function, so you are basically asking this
if(array % 2 === 0) arr.push(array);
Arrays in JavaScript behave interestingly when used in conditional statements, and in this situation the array essentially has toString called on it (more in depth here: https://stackoverflow.com/a/10556035/1026459 , but basically when you have object === number then it will attempt to use toPrimitive on the object which results in a string), which makes it
if("1,2,3" % 2 === 0)
which is false. As a result arr is unchanged, and returned in its original state of [].

JavaScript function that takes an array as a parameter

I am trying to create a JavaScript function that takes an array as a parameter and returns the first item in the array. This should work for an array of any size. Here is what I have so far, it appears to work just fine in the console but my instructor says there's a better way to do this:
var array = [];
function numbaOne(array) {
for (var i = 0; i < array.length; i++) {
console.log(array[0])
};
}
Any help would be appreciated. I've read about data structures and arrays but can't figure out how to simplify or make this better.
What you are doing is looping over the array and printing out the first item each time. You just want:
var array = [...];
function numbaOne(array) {
console.log(array[0]); // Print out the first value of the array
return array[0]; // Return the first value of the array
}
There is one edge case here. If the array is empty, then the function will fail because array[0] will be undefined.
So, a more complete version might be:
var array = [...];
function numbaOne(array) {
if(array.length > 0) { // Check if there is anything in the array
console.log(array[0]);
return array[0];
} else { // If there isn't, let's return something "bad"
console.log("The array is empty!");
return undefined;
}
}

Categories