Update: on newer browsers - use .fill: Array(1000).fill('') will create an array of 1000 empty strings.
Yes, there is a way:
var n = 1000;
Array(n).join(".").split("."); // now contains n empty strings.
I'd probably use the loop though, it conveys intent clearer.
function repeat(num,whatTo){
var arr = [];
for(var i=0;i<num;i++){
arr.push(whatTo);
}
return arr;
}
That way, it's perfectly clear what's being done and you can reuse it.
Answer from Benjamin Gruenbaum on Stack OverflowUpdate: on newer browsers - use .fill: Array(1000).fill('') will create an array of 1000 empty strings.
Yes, there is a way:
var n = 1000;
Array(n).join(".").split("."); // now contains n empty strings.
I'd probably use the loop though, it conveys intent clearer.
function repeat(num,whatTo){
var arr = [];
for(var i=0;i<num;i++){
arr.push(whatTo);
}
return arr;
}
That way, it's perfectly clear what's being done and you can reuse it.
You can get an array defining the size and fill it with some tokens:
const arr = Array(size).fill("");
Videos
You can check by looping through the array with a simple for, like this:
function NoneEmpty(arr) {
for(var i=0; i<arr.length; i++) {
if(arr[i] === "") return false;
}
return true;
}
You can give it a try here, the reason we're not using .indexOf() here is lack of support in IE, otherwise it'd be even simpler like this:
function NoneEmpty(arr) {
return arr.indexOf("") === -1;
}
But alas, IE doesn't support this function on arrays, at least not yet.
You have to check in through loop.
function checkArray(my_arr){
for(var i=0;i<my_arr.length;i++){
if(my_arr[i] === "")
return false;
}
return true;
}
The definition of string array should be:
// instead of this
// var errors: [string];
// we need this
var errors: string[];
errors = [];
Note: another issue could be the parameter key here
...forEach(function (key) {...
I would guess that we often should declare two of them, because first is very often value, second key/index
Object.keys(response.data.modelState)
.forEach(function (value, key) {
errors.push.apply(errors, response.data.modelState[key]);
});
And even, we should use arrow function, to get the parent as this
Object.keys(response.data.modelState)
.forEach( (value, key) => {
errors.push.apply(errors, response.data.modelState[key]);
});
Missing an obvious answer, needed when not assigning it to a variable: [] as string[]
A few simple ways:
var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];
arr.filter(n => n)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Number)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Boolean)
// [1, 2, 3, -3, 4, 4, 5, 6]
or - Classic way: simple iteration
var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
len = arr.length, i;
for(i = 0; i < len; i++ )
arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array
arr.splice(0 , len); // cut the array and leave only the non-empty values
// [1,2,3,3,[],Object{},5,6]
jQuery:
var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
arr = $.grep(arr, n => n == 0 || n);
// [1, 2, 3, 3, 0, 4, 4, 5, 6]
EDIT: This question was answered almost nine years ago when there were not many useful built-in methods in the Array.prototype.
Now, certainly, I would recommend you to use the filter method.
Take in mind that this method will return you a new array with the elements that pass the criteria of the callback function you provide to it.
For example, if you want to remove null or undefined values:
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
var filtered = array.filter(function (el) {
return el != null;
});
console.log(filtered);
It will depend on what you consider to be "empty" for example, if you were dealing with strings, the above function wouldn't remove elements that are an empty string.
One typical pattern that I see often used is to remove elements that are falsy, which include an empty string "", 0, NaN, null, undefined, and false.
You can pass to the filter method, the Boolean constructor function, or return the same element in the filter criteria function, for example:
var filtered = array.filter(Boolean);
Or
var filtered = array.filter(function(el) { return el; });
In both ways, this works because the filter method in the first case, calls the Boolean constructor as a function, converting the value, and in the second case, the filter method internally turns the return value of the callback implicitly to Boolean.
If you are working with sparse arrays, and you are trying to get rid of the "holes", you can use the filter method passing a callback that returns true, for example:
var sparseArray = [0, , , 1, , , , , 2, , , , 3],
cleanArray = sparseArray.filter(function () { return true });
console.log(cleanArray); // [ 0, 1, 2, 3 ]
Old answer: Don't do this!
I use this method, extending the native Array prototype:
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);
Or you can simply push the existing elements into other array:
// Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string)
function cleanArray(actual) {
var newArray = new Array();
for (var i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i]);
}
}
return newArray;
}
cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);
You could use the filter like:
arr = arr.filter(item => item);
Example:
let arr = ['One', 'Two', '', 'Four', '', ''];
arr = arr.filter(item => item);
console.log(arr);
// Result
// ['One', 'Two', 'Four']
Because an empty string evaluates to boolean false.
It works with all falsy values like 0, false, null, undefined, '', etc.
DEMO
If you want to keep some values like number 0 (zero) you could use item !== undefined. This filters only undefined values. Keep in mind to trim your string or check with regex to ensure empty strings without whitespaces.
Try filtering with the Boolean function:
columns.filter(Boolean)
This will filter out all falsy values
Ways to clear an existing array A:
Method 1
(this was my original answer to the question)
A = [];
This code will set the variable A to a new empty array. This is perfect if you don't have references to the original array A anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable A.
This is also the fastest solution.
This code sample shows the issue you can encounter when using this method:
var arr1 = ['a','b','c','d','e','f'];
var arr2 = arr1; // Reference arr1 by another variable
arr1 = [];
console.log(arr2); // Output ['a','b','c','d','e','f']
Method 2 (as suggested by Matthew Crumley)
A.length = 0
This will clear the existing array by setting its length to 0. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property.
Method 3 (as suggested by Anthony)
A.splice(0,A.length)
Using .splice() will work perfectly, but since the .splice() function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever.
Method 4 (as suggested by tanguy_k)
while(A.length > 0) {
A.pop();
}
This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer.
Performance
Of all the methods of clearing an existing array, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this benchmark.
As pointed out by Diadistis in their answer below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty.
The following benchmark fixes this flaw: http://jsben.ch/#/hyj65. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array).
This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here.
If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero:
A.length = 0;
Beside the proposed using of Array#toString method, I suggest to use Array#join with an empty string as separator and then test the result. The advantage is, it works for an arbitrary count of elements inside of the array.
var bool = array.join('') ? 'not all empty string' : 'all empty string';
['', ''] == ['', ''] returns false because in JavaScript arrays are objects, and objects in JavaScript have reference semantics. Comparing objects to each other actually compares their reference IDs, which will be different for different references. So, even though both sides of == are the "same" array, they are different references.
If you want to check that an array only contains empty strings, use Array.prototype.every as in the following:
myArray = ['']
console.log(myArray.every(el => el === '')) // true
myArray = []
console.log(myArray.every(el => el === '')) // true
myArray = ['test']
console.log(myArray.every(el => el === '')) // false
If you are in an environment without ES6 support, you can swap the el => el === '' for function(el) { return el === '' }.