Javascript array non undefined element count - javascript

I create an array with let arr = new Array(99999) but I don't fill it up to arr.length which is 99999, how can I know how much actual, non undefined elements do I have in this array?
Is there a better way than to look for the first undefined?

You could use Array#forEach, which skips sparse elements.
let array = new Array(99999),
count = 0;
array[30] = undefined;
array.forEach(_ => count++);
console.log(count);
The same with Array#reduce
let array = new Array(99999),
count = 0;
array[30] = undefined;
count = array.reduce(c => c + 1, 0);
console.log(count);
For filtering non sparse/dense elements, you could use a callback which returns for every element true.
Maybe this link helps a bit to understand the mechanic of a sparse array: JavaScript: sparse arrays vs. dense arrays.
let array = new Array(99999),
nonsparsed;
array[30] = undefined;
nonsparsed = array.filter(_ => true);
console.log(nonsparsed);
console.log(nonsparsed.length);

The fastest & simplest way to filter items in an array is to... well... use the .filter() function, to filter out only the elements that are valid (non undefined in your case), and then check the .length of the result...
function isValid(value) {
return value != undefined;
}
var arr = [12, undefined, "blabla", ,true, 44];
var filtered = arr.filter(isValid);
console.log(filtered); // [12, "blabla", true, 44]

Related

count words unique in array JavaScript

I have a Array, with a series of words that it collects in another function. What I intend is to count and separate those words that are unique and in the event that it is repeated do not count them. I've come this far, but the code stays in the first for. The goal is to count unique words in the array.
let arrayTemp = [];
Array1.forEach((item) => {
if(arrayTemp[0]){
arrayTemp[0] = item.perfilRoot;
}
for(let i = 0; i < arrayTemp.length; i++){
if(item.perfilRoot != arrayTemp[i]){
arrayTemp.push(item.perfilRoot);
}else{
break;
}
}
});
Convert to Set and check size
unique = new Set(YourArray);
console.log(unique.size)
You can try using Set which is an object that lets you store unique values.
const valuesYouWant = Array1.map(item => item.perfilRoot); // new array with values you want from Array1
const uniqueValues = [...new Set(valuesYouWant)]; // new array with unique values from array valuesYouWant
console.log(uniqueValues); // this will log your unique values
console.log(uniqueValues.length); // this will log the length of the new created array holding the unique values
You can consider using a Set.
array = [1,1,2,3,4,4,5];
unique = [...new Set(array)];
console.log (unique.length);
you can use Sets:
let arr = [1, 2, 3, 2, 3, 1]
console.log(new Set(arr).size)
or you can use object like maps to count uniques keys:
let arr = ['dog', 'dog', 'cat', 'squirrel', 'hawk', 'what a good dog'];
let m = {};
// count uniques words in array
arr.forEach(word => m[word] = 1);
// prints uniques counters
console.log('count:', Object.keys(m).length)
Since you only want to count the unique words, Set will not work. The code below looks at the array and only if the word is only found once in Array1 does it add it to arrayTemp
let arrayTemp = [];
Array1.map(a=>a.perfilRoot).forEach((item, index) => {
if (index +1 < Array1.length && Array1.slice(index +1).indexOf(item) === -1) arrayTemp.push(item);
});
console.log(arrayTemp);
console.log('number of unique words', arrayTemp.length);

Array.slice using index number contained in another array

I have two arrays.I'm trying to remove some elements from [arr] at index numbers in [removeIndex].
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
for (let i = 0; i < removeIndex.length;i++){
arr.splice(removeIndex[i],1);
}
console.log(arr)
// output Array(5) [ 1, 1, 0, 1, 1 ]
//expected [ 1,1,1,1,1]
Both the 0's are at arr[2] and arr[3] position and should get removed,however the above code doesnt work.I suspect it has to do with the loop re-arranging the index numbers.Any alternate solution?
You definitely suspect correctly about why this is happening. The easiest way I can think of to do what you're after is to use the not-often-used second argument to the callback function passed to the filter method, which takes an element's index:
arr = arr.filter((elt, index) => removeIndex.indexOf(index) == -1);
You can use Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and Array.prototype.includes()
The includes() method determines whether an array includes a certain element, returning true or false as appropriate.
Pass index as the second parameter to check whether that index includes or not in removeIndex. Return the element only if the current index does not exist in removeIndex array:
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
arr = arr.filter((i,idx) => !removeIndex.includes(idx));
console.log(arr); //[ 1,1,1,1,1]
I would use filter and come up with this clean code:
var removeIndex = [2,3];
var arr = [1,1,0,0,1,1,1];
var newArr = arr.filter(el => el !== 0);
console.log(newArr);
// [1,1,1,1,1]
As stated in the comments, you mutate the array so the next time you loop through the array it's items will be changed and you won't have the same items at the same indexes. There is a fairly simple solution for your particular example :
var removeIndex = [2,3].sort(); // This won't work with [3,2] for example
var arr = [1,1,0,0,1,1,1];
for (let i = 0; i < removeIndex.length; i++){
arr.splice(removeIndex[i] - i, 1);
}
console.log(arr)
But I'd suggest using an immutable solution with .filter for example, like suggested in the comments

Reactjs trying to merge arrays

Let's say I have two array's
let array1 = ["H","E","", "","O","","","R","L","D"];
let array2 = ["","","L","L","","W","O","","",""];
I want to merge them such that they would then contain:
array3 = ["H","E","L", "L","O","W","O","R","L","D"];
How would I achieve this?
To be more clear I have a target array which is array3 an empty array and then I'm generating random characters and if they match array3 adding them to the blank array in the specific position with react state. It is just not storing the position and character each time but just changing it. SO my idea is to set the state such that I merge the current state with the new characters that are found.
TLDR:- Brute forcing Hello World meme.
You can use Array.prototype.map() to create a new array array3 out of iterating over array1 and get the l (letters) and if any l evaluates to falsey then get the letter at the same i (index) in the array2.
Note that instead of declaring your arrays with let you should always use const because it makes code easier to read within its scope, and const variable always refers to the same object.
Code example:
const array1 = ["H","E","", "","O","","","R","L","D"];
const array2 = ["","","L","L","","W","O","","",""];
const array3 = array1.map((l, i) => l || array2[i]);
console.log(array3);
Try it:
let arr1 = ["H","E","", "","O","","","R","L","D"];
let arr2 = ["","","L","L","","W","O","","",""];
let arr3 = [];
arr1.forEach((val, index) => {
if (val === '') {
arr3[index] = arr2[index];
} else {
arr3[index] = val;
}
});
console.log(arr3);

How to remove undefined and create a new array Javascript?

I have the following array:
var imagesList = [undefined x 1, cars.jpg, undefined x 1, boats.jpg];
How do I filter out the undefined? so I can get it as follows:
var imagesShow = [cars.jpg, boats.jpg];
I have not found much documentation on getting rid of undefined in an array using javascript.
You could use Array#filter with Boolean as callback for truthy values.
var imagesList = [undefined, 'cars.jpg', undefined, 'boats.jpg'],
imagesShow = imagesList.filter(Boolean);
console.log(imagesShow);
Use Array#filter:
var imagesList = [undefined, 'cars.jpg', undefined, 'boats.jpg'];
var result = imagesList.filter(function(v) {
return v !== undefined;
})
console.log(result);
Try using the Array.filter function
var imagesShow = imagesList.filter(function (value) {
return value != undefined;
};
Any array element that does not pass the check in the callback function above will be filtered out - in this case, if the element is undefined.
Use Array.Filter
var imagesList = [undefined, 'cars.jpg', undefined, 'boats.jpg'];
var result = imagesList.filter(function( element ) {
return element !== undefined;
});
console.log(result);
Try Array.filter() method with ES6 Arrow function expression.
var imagesList = [undefined, "cars.jpg", undefined, "boats.jpg"];
var filteredList = imagesList.filter(item => { return item !== undefined });
console.log(filteredList);
By displaying undefined x 2, your array clearly indicates that it's a sparse one which means you don't have any undefined items. You just don't have the keys to hold items to start with.
OK you may have and wish to keep proper void 0 or undefined items (in which case all of the above solutions will fail) or a numeric value 0 or null object item (in which case the accepted answer will fail).
In order to convert a sparse array to dense form the most efficient method would be a for in loop (or Object.keys()).
So for sparse array looping it's best to use
var res = [],
a = [];
a[1] = "cars.jpg";
a[5] = null;
a[999999] = "beauty.jpg";
// [undefined × 1, "cars.jpg", undefined × 3, null, undefined × 999993, "beauty.jpg"]
function dense(a){
var r = [];
for (i in a) r.push(a[i]);
return r;
}
console.time("test");
res = dense(a);
console.timeEnd("test");
console.log(res);
Now lets compare the above code with an elegant filtering solution;
var res = [],
a = [];
a[1] = "cars.jpg";
a[5] = null;
a[999999] = "beauty.jpg";
// [undefined × 1, "cars.jpg", undefined × 3, null, undefined × 999993, "beauty.jpg"]
console.time("test");
res = a.filter(Boolean);
console.timeEnd("test");
console.log(res);
So as you see null is disappeared and it is slower since it checks all non existing keys. However with for in loop keeping the falsey values or not is totally under your control.

How to empty an javascript array?

var arr = [-3, -34, 1, 32, -100];
How can I remove all items and just leave an empty array?
And is it a good idea to use this?
arr = [];
Thank you very much!
If there are no other references to that array, then just create a new empty array over top of the old one:
array = [];
If you need to modify an existing array—if, for instance, there's a reference to that array stored elsewhere:
var array1 = [-3, -34, 1, 32, -100];
var array2 = array1;
// This.
array1.length = 0;
// Or this.
while (array1.length > 0) {
array1.pop();
}
// Now both are empty.
assert(array2.length == 0);
the simple, easy and safe way to do it is :
arr.length = 0;
making a new instance of array, redirects the reference to one another new instance, but didn't free old one.
one of those two:
var a = Array();
var a = [];
Just as you say:
arr = [];
Using arr = []; to empty the array is far more efficient than doing something like looping and unsetting each key, or unsetting and then recreating the object.
Out of box idea:
while(arr.length) arr.pop();
Ways to clean/empty an array
This is perfect if you do not have any references from other places. (substitution with a new array)
arr = []
This Would not free up the objects in this array and may have memory implications. (setting prop length to 0)
arr.length = 0
Remove all elements from an array and actually clean the original array. (splicing the whole array)
arr.splice(0,arr.length)

Categories

Resources