I used the code described here but now, when I do a "for ... in ..." cicle, it gets the function "indexOf" as an index position of the array...
Example Code:
var the_array=new Array();
for (key in the_array){
console.log(key +" - "+the_array[key]);
}
This code shows this in the console:
indexOf - function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
How could I prevent the function from appearing as a key on the array?
Btw, I know that I can use the inArray function of jquery but, in this case, I would like to use the "indexOf" function...
It's a bad idea to use for...in on arrays, for this and other reasons. See my answer here:
Why is 'for(var item in list)' with arrays considered bad practice in JavaScript?
Related
I can not finish one of the easiest kata on codewars.
Want to understand where am I wrong!
Instructions: Sum all the numbers of the array except the highest and
the lowest element (the value, not the index!). (The highest/lowest
element is respectively only one element at each edge, even if there
are more than one with the same value!) If array is empty, null or
None, or if only 1 Element exists, return 0.
function sumArray(array) {
var finalSum = 0;
if (array != null || !array) {
for (var i = 0; i < array.length; i++) {
finalSum += array[i];
}
if (array.length === 0 || array.length <= 1) {
return 0;
} else {
return finalSum - Math.max(...array) - Math.min(...array);
}
}
}
Everything seems fine and should work, but it is not passing final tests.
TypeError: Cannot read property 'length' of null
I tried to add in the first if typeof array != 'null', typeof array != 'undefined' but it did not help...
In Javascript, the return of typeof of a null will be an object. That is why your first if doesn't work. You check if its not equal to null and its true, because the return will be object. Read more here ECMAScript null.
More proof on this, pull out a console and type the following.
a = null
typeof array // will return "object"
a != null // will return false, even if we attributed the value of a to null.
a !== null // will false also
a == null // will return true, so let's use this !
I assume that the error you are getting is when the test is sumArray(null) or sumArray(). In order to properly return 0, you have to do this.
function sumArray(array) {
var finalSum = 0;
if (array == null)
return 0;
if (array != null || !array) {
for (var i = 0; i < array.length; i++) {
finalSum += array[i];
}
if (array.length === 0 || array.length <= 1) {
return 0;
} else {
return finalSum - Math.max(...array) - Math.min(...array);
}
}
}
For some weird reason, using a array == null will return the proper return value (true if your array is null). (I haven't read much on why).
if(typeof array !== "undefined" && typeof array !== "null" )
You can try this.
check like this.
if(array && array.length) {
for (var i = 0; i < array.length; i++) {
finalSum += array[i];
}
if (array.length === 0 || array.length <= 1) {
return 0;
} else {
return finalSum - Math.max(...array) - Math.min(...array);
}
}
I was looking on MDN for a polyfill for Array.prototype.includes() and I came across the Object() syntax below:
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement /*, fromIndex*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.includes called on null or undefined');
}
//This is the line in question
var O = Object(this);
var len = parseInt(O.length, 10) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1], 10) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {k = 0;}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement ||
(searchElement !== searchElement && currentElement !== currentElement)) { // NaN !== NaN
return true;
}
k++;
}
return false;
};
}
What is Object(this) doing and what is the purpose of this in this case?
Object(...) converts the passed value to an object. It simply returns the value itself if it is already an object, otherwise wit will create a new object and return that.
From the spec:
When Object is called as a function rather than as a constructor, it performs a type conversion.
Example:
var obj = Object("foo");
// same as
// var obj = new String("foo");
what is the purpose of this in this case?
It ensures that the value is an object, not a primitive. The implementation just follows the spec:
Let O be ? ToObject(this value).
it looks like easy but I kind of stuck in trying to figure out how to filter data before pushing json data into javascript array.
//push data into javascript array [timestamp,value]
dataJSON2 = [];
for (i in parsed2) {
if (parsed2[i].value == 'open' || parsed2[i].value == 'true' ) {
thevalue = 1;
} else if (parsed2[i].value == 'closed' || parsed2[i].value == 'false' ) {
thevalue = 0;
} else {
thevalue = parsed2[i].value;
}
dataJSON2.push( [ (parsed2[i].timestamp),
parseFloat (thevalue) ] );
}
what I am trying to accomplish is if current thevalue var is the same with the previous thevalue then it would discard the data and go to the next i until it return different value.
It would be easy if using for looping but I don't know different way to push json object rather than for..in, nor to use filtering i value before pushing it.
var dataJSON2 = [], previous;
for (i in parsed2) {
if (parsed2[i].value === 'open' || parsed2[i].value === 'true' ) {
thevalue = 1;
} else if (parsed2[i].value === 'closed' || parsed2[i].value === 'false' ) {
thevalue = 0;
} else {
thevalue = parsed2[i].value;
}
if (previous === thevalue) continue;
previous = thevalue;
dataJSON2.push( [ (parsed2[i].timestamp), parseFloat (thevalue) ] );
}
This would check for previous value with the current value and skip it if they are same
dataJSON2 = [];
var lastVal = parsed2 && parsed2[0];
for (var i = 1; i < parsed2.length; i++) {
if (lastVal !== parsed2[i].value) {
dataJSON2.push([(parsed2[i].timestamp), parseFloat(parsed2[i].value)]);
lastVal = parsed2[i];
}
}
Extracted from Array.indexOf from MDN
Create a function like this
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
'use strict';
if (this == null) {
throw new TypeError();
}
var n, k, t = Object(this),
len = t.length >>> 0;
if (len === 0) {
return -1;
}
n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
for (k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
and use indexOf like this
if (dataJSON2.indexOf( [ (parsed2[i].timestamp), parseFloat (thevalue) ] ) == -1){
dataJSON2.push( [ (parsed2[i].timestamp), parseFloat (thevalue) ] );
}
I am trying to use a FOR loop to display contents of an array.
the function I want to create is similar to underscore.js _.rest function except the objective is touse a FOR loop.
rest(anyArray, n);
so if I were to enter "rest([1,2,3,4,5], 3);", I want to return "[4,5]".
Here is what I have and it does not work:
rest: function (anyArray, n) {
var isArray = (anyArray instanceof Array),
isNum = (typeof n === 'number'),
result = new Array,
valRange = (n >= 0);
if (isArray && isNum) {
for (len = anyArray.length, i = 0, j = (len - (n + len)); i < j, n < len; i++, j++) {
result[i] = anyArray[j];
}
return result;
}
}
rest: function (anyArray, n) {
return anyArray.slice(n);
}
rest: function (anyArray, n) {
var output = [];
for (; n < anyArray.length; n++) {
output.push(anyArray[n]);
}
return output;
}
The part that leads to "not working" is j = (len - (n + len)): Essentially, you say j = n, and then you are looping while i < j. I'd expect that what you actually want is j < len. Also, you should add the var keyword:
rest: function(anyArray, n){
var isArray = (anyArray instanceof Array),
isNum = (typeof n === 'number'),
result = [];
if (isArray && isNum) {
for (var len = anyArray.length, i = 0, j = n; j < len; i++, j++) {
result[i] = anyArray[j];
}
return result;
}
// else?
}
Of course, just using the native slice method would be much easier.
can some one tell me how can i remove string element from an array
i have google this and all i get is removing by index number
my example :
var myarray = ["xyz" , "abc" , "def"] ;
var removeMe = "abc" ;
myarray.remove(removeMe) ;
consle.log(myarray) ;
this is what i get from the console :
Uncaught TypeError: Object xyz,abc,def has no method 'remove'
jsfiddle
Since you're using jQuery
myarray.splice($.inArray("abc", myarray), 1);
EDIT
If the item isn't in the array, this 'one-liner' will likely throw an error. Something a little better
var index = $.inArray("abc", myarray);
if (index>=0) myarray.splice(index, 1);
From https://stackoverflow.com/a/3955096/711129:
Array.prototype.remove= function(){
var what, a= arguments, L= a.length, ax;
while(L && this.length){
what= a[--L];
while((ax= this.indexOf(what))!= -1){
this.splice(ax, 1);
}
}
return this;
}
var ary = ['three', 'seven', 'eleven'];
ary.remove('seven')
or, making it a global function:
function removeA(arr){
var what, a= arguments, L= a.length, ax;
while(L> 1 && arr.length){
what= a[--L];
while((ax= arr.indexOf(what))!= -1){
arr.splice(ax, 1);
}
}
return arr;
}
var ary= ['three','seven','eleven'];
removeA(ary,'seven')
You have to make a function yourself. You can either loop over the array and remove the element from there, or have this function do it for you. Either way, it is not a standard JS feature.
Try like below,
myarray.splice(myarray.indexOf(removeMe),1);
You can add this below script (from MDN) for browsers that doesn't support indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 0) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
}
}
more simple solution
var myarray = ["xyz" , "abc" , "def"];
var removeMe = "abc";
var theNewArray = myarray.filter(s => s !== removeMe);
console.log(theNewArray); // will return ["xyz" , "def"]