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.
Related
I am expecting permutation array to be as below
but the result i am getting on executing the code in the snippet is not what i want.
can someone explain me, why isnt the output as i expected.
permutation [[ "a","b","a"],["b","a","a"],["a","a","b"]]
function permAlone(str) {
const createPermutation = () => {
let arr = Array.from(str);
let permutation = [];
Array.from(str).forEach(_ele => {
const first = arr.shift();
arr = arr.concat(first);
permutation.push(arr)
});
console.log('permutation',permutation);
};
createPermutation();
return str;
}
permAlone("aab");
When you push arr to permutation it keeps a reference, when you modify arr on the subsequent iterations you modify it affects the content of the permutation array, a simple way force a copy of an array is using the method slice.
function permAlone(str) {
const createPermutation = () => {
let arr = Array.from(str);
let permutation = [];
Array.from(str).forEach(_ele => {
const first = arr.shift();
arr = arr.concat(first);
permutation.push(arr.slice())
});
console.log('permutation',permutation);
};
createPermutation();
return str;
}
permAlone("aab");
clarification
In response to your comment I am crating a simpler example.
const arr1 = []
const arr = []
arr.push(1)
arr1.push(arr)
console.log(arr1) // here you se what you would expect
arr.push(2) // arr1 has a reference to this object
console.log(arr1) // here you see that arr1 changed
If you push a slice this will add a copy of arr, instead of a reference to it
const arr1 = []
const arr = []
arr.push(1)
arr1.push(arr.slice()) // what is added is a copy of arr
console.log(arr1) // here you se what you would expect
arr.push(2) // arr1 does not have a reference to this object
console.log(arr1) // here you see that arr1 is not changed
The problem in your code was you were pushing deep copy of your arr array. Instead of that you should do shallow copy with using slice() method. When you deep copy the array it passes its address which changes its value after its last iteration instead of that you should pass array's value using slice method so that your code will work fine.
function permAlone(str) {
const createPermutation = () => {
let arr = Array.from(str);
let permutation = [];
Array.from(str).forEach(_ele => {
const first = arr.shift();
arr = arr.concat(first);
permutation.push(arr.slice())
});
console.log('permutation',permutation);
};
createPermutation();
return str;
}
permAlone("aab");
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
I have got this code:
var test = [[1,1], "b","a"];
function findArray(element) {
return element == [1,1];
}
console.log(test.find(findArray));
It returns:
undefined
What should I do to find the [1,1] array inside of the test array? (I do not want to loop through it though)
You can't compare two objects with === or == since they are references and will evaluate to true only if they are pointing to the same address.
You need to match each element from first array with respective index in second array to check for similarity, you can use every.
var test = [ [1, 1], "b", "a"];
function findArray(element) {
if(Array.isArray(element)){
let arrayToMatchWith = [1,1]
if(element.length === arrayToMatchWith.length){
return element.every((v,i)=> v === arrayToMatchWith[i])
}
}
return false
}
console.log(test.find(findArray));
console.log([[1,2]].find(findArray));
console.log([[1,1,1]].find(findArray));
console.log([[1]].find(findArray));
Could I pass the searched array as an argument?
Yes you can. Here I am using a curried function:
var test = [[1, 1], "b", "a"];
let curried = (arr) => (element) => {
if (Array.isArray(element)) {
if (element.length === arr.length) {
return element.every((v, i) => v === arr[i])
}
}
return false
}
let curried1 = curried([1,1])
console.log(test.find(curried1));
let curried2 = curried([1,2,2])
console.log([[1, 2]].find(curried2));
let curried3 = curried([1,1,1])
console.log([[1, 1, 1]].find(curried3));
let curried4 = curried([1])
console.log([[1]].find(curried4));
The array literal in your comparison is a different object than the array inside your original array. If you derive a comparable entity from each array, you can check for that inside the find method. One way to do it is by calling the toString method.
This is only required if you really don't want to loop through the array for comparison.
var test = [[1,1], "b","a"];
function findArray(element) {
if (element.constructor === Array)
return element.toString() == [1,1].toString();
}
console.log(test.find(findArray));
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.
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();