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();
Related
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
var arr = [30];
delete arr[0];
if (arr.length == 0) {
alert("empty");
}
This code won't work only because of delete.
Is there an ultimate way to check if the array is empty no matter what?
Thanks :)
You can use Object.values() to get actual values from the array. If the length of the values array is 0, then the array is empty by your definition.
const checkIfSparseIsEmpty = arr => !Object.values(arr).length
var arr1 = [30];
delete arr1[0];
console.log(checkIfSparseIsEmpty(arr1)) // true
var arr2 = [1, 2, 3]
delete arr2[0]
delete arr2[1]
console.log(checkIfSparseIsEmpty(arr2)) // false
console.log(checkIfSparseIsEmpty(Array(10))) // true
The reason behind the expected behaviour is that when you use the delete operator, it replaces the element by undefined, and since the length doesn't change the above check does not work.
One of the ways to effectively delete an element from the array is to use the filer array function.
Example:
function deleter(arr, toDelete) {
let newArray = arr.filter((ar) => {
return ar !== toDelete;
})
return newArray;
}
let array = [1,2,3,4,5]
console.log(deleter(array, 5));
Now to check if an element exists in an array, you can use the indexOf method available on the array prototype.
Following is an example:
function deleter(arr, toDelete) {
let newArray = arr.filter((ar) => {
return ar !== toDelete;
})
return newArray;
}
let array = [1,2,3,4,5]
let toDelete = 5;
let newArr = deleter(array, toDelete);
console.log(newArr.indexOf(toDelete))
// -1 corresponds to the element not found.
I would like to return both the inner and outer array such as the following: [[3],[4],[5]];
This does not work:
var arr = [[1],[2],[3],[4],[5]];
arr.filter(function(el){
return el.filter(function(inner){
return inner >= 3;
});
});
This does not work either:
var arr = [[1],[2],[3],[4],[5]];
arr.map(function(el){
return el.filter(function(inner){
return inner >= 3;
});
});
You can use array destructuring to get easy access to the inner array elements in the callback function:
const array = [[1],[2],[3],[4],[5]];
const filtered = array.filter(([inner]) => inner >= 3);
console.log(array); // original
console.log(filtered); // filtered
map() and filter() functions don't mutate the array, they return a new array with the resulting items.
In the code you show us you're not assigning the result anywhere, also, you're trying to compare an array with a number:
If you wanted to return the values inside of their wrapping arrays, you would do it like this:
var arr = [[1],[2],[3],[4],[5]];
var newArr = arr.filter(function(inner){
return inner[0] >= 3;
});
// newArr = [[3], [4], [5]]
you don't need the map function if you're only filtering.
I have an array like this:
var arrayTemp = [
{"0":["Z",59]},
{"1":["D",53]},
{"2":["6",26]},
{"3":["3",19]},
{"4":["Y",10]},
{"5":["H",7]},
{"6":["G",5]},
{"7":["2",5]}
];
I need an output similar to the below one,
var arrayTemp = [
{"Z":59},
{"D":53},
{"6":26},
{"3":19},
{"Y":10},
{"H":7},
{"G":5},
{"2":5}
];
How do I achieve this? I would like this to be achieved with the help of json, underscore or JavaScript.
Using Array.prototype.map() you could iterate trough each element of the original array and create the required objects, returning them as new elements in a new array.
var newArray = arrayTemp.map(function(e, index) {
var x = {};
x[e[index][0]] = e[index][1];
return x;
})
DEMO - Using Array.prototype.map() to create the new array
Something like this:
var newArray = arrayTemp.map(function(e) {
var index = Object.keys(e).shift(),
innerElement = e[index],
ret = {};
ret[innerElement[0]] = innerElement[1];
return ret;
})
JsFiddle to test.
With underscore:
var newArr = _.map(arrayTemp, function(item){
for (var i in item){
var o = {};
o[item[i][0]] = item[i][1];
return o;
}
});
Although #François_Wahl's solution is the better one in my esteem using the native Array.prototype.map().
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');});