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"]
Related
How to write in javascript(w/wth JQuery) to find values that intersect between arrays?
It should be like
var a = [1,2,3]
var b = [2,4,5]
var c = [2,3,6]
and the intersect function should returns array with value {2}. If possible it could applicable for any number of arrays.
Thanks
There are many ways to achieve this.
Since you are using jQuery I will suggest use grep function to filter the value that are present in all three array.
var a = [1, 2, 3]
var b = [2, 4, 5]
var c = [2, 3, 6]
var result = $.grep(a, function(value, index) {
return b.indexOf(value) > -1 && c.indexOf(value) > -1;
})
console.log(result)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Explanation: Loop over any array and filter out the values that are present in other array.
Update (for multimidensional array):
Concept - flatten the multidimensional array that is transform [[1,2],3,4] to [1,2,3,4] and then use the same logic used for single dimensional array.
Example:
var a = [
[1, 4], 2, 3
]
var b = [2, 4, 5]
var c = [2, 3, 6, [4, 7]]
//flatten the array's
//[1,4,2,3]
var aFlattened = $.map(a, function(n) {
return n;
})
//[2,4,5]
var bFlattened = $.map(b, function(n) {
return n;
})
//[2,3,6,4,7]
var cFlattened = $.map(c, function(n) {
return n;
})
var result = $.grep(aFlattened, function(value) {
return (bFlattened.indexOf(value) > -1 && cFlattened.indexOf(value) > -1);
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
// First this is how you declare an array
var a = [1,2,3];
var b = [2,4,5];
var c = [2,3,6];
// Second, this function should handle undetermined number of parameters (so arguments should be used)
function intersect(){
var args = arguments;
// if no array is passed then return empty array
if(args.length == 0) return [];
// for optimisation lets find the smallest array
var imin = 0;
for(var i = 1; i < args.length; i++)
if(args[i].length < args[imin].length) imin = i;
var smallest = Array.prototype.splice.call(args, imin, 1)[0];
return smallest.reduce(function(a, e){
for(var i = 0; i < args.length; i++)
if(args[i].indexOf(e) == -1) return a;
a.push(e);
return a;
}, []);
}
console.log(intersect(a, b, c));
First of all '{}' means Object in JavaScript.
Here is my suggestion.(this is another way of doing it)
// declarations
var a = [1,2,3];
var b = [2,4,5];
var c = [2,3,6];
// filter property of array
a.filter(function(val) {
if (b.indexOf(val) > -1 && c.indexOf(val) > -1)
return val;
});
what it does is it checks for each element in array 'a' and checks if that value is present in array 'b' and array 'c'. If it is true it returns the value. Simple!!!. The above code should work for String as well but it wouldn't work for IE < 9, so be careful.
// Intersecting 2 ordered lists of length n and m is O(n+m)
// This can be sped up by skipping elements
// The stepsize is determined by the ratio of lengths of the lists
// The skipped elements need to be checked after skipping some elements:
// In the case of step size 2 : Check the previous element
// In case step size>2 : Binary search the previously skipped range
// This results in the best case complexity of O(n+n), if n<m
// or the more propable complexity of O(n+n+n*log2(m/n)), if n<m
function binarySearch(array, value, start = 0, end = array.length) {
var j = start,
length = end;
while (j < length) {
var i = (length + j - 1) >> 1; // move the pointer to
if (value > array[i])
j = i + 1;
else if (value < array[i])
length = i;
else
return i;
}
return -1;
}
function intersect2OrderedSets(a, b) {
var j = 0;
var k = 0;
var ratio = ~~(b.length / a.length) - 1 || 1;
var result = [];
var index;
switch (ratio) {
case 1:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k++;
if (k >= b.length) break;
}
}
break;
case 2:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k += 2;
if (k - 1 >= b.length) break;
if (a[j] <= b[k - 1]) k--;
}
}
break;
default:
while (j < a.length) {
if (a[j] === b[k]) {
result.push(a[j]);
j++;
k++;
} else if (a[j] < b[k]) {
while (a[j] < b[k]) j++;
} else {
while (b[k] < a[j]) k += ratio;
index = binarySearch(b, a[j], k - ratio + 1, k + 1 < b.length ? k + 1 : b.length - 1);
if (index > -1) {
result.push(a[j]);
j++;
k = index + 1;
} else {
j++;
k = k - ratio + 1;
}
if (k >= b.length) break;
}
}
}
return result;
}
function intersectOrderedSets() {
var shortest = 0;
for (var i = 1; i < arguments.length; i++)
if (arguments[i].length < arguments[shortest].length) shortest = i;
var result = arguments[shortest];
for (var i = 0, a, b, j, k, ratio, index; i < arguments.length; i++) {
if (result.length === 0) return result;
if (i === shortest) continue;
a = result;
b = arguments[i];
result = intersect2OrderedSets(a, b);
}
return result;
}
How to use:
intersectOrderedSets(a,b,c);
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 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?
I need to search for the presence of an array inside an array. It is similar to jQuery.inArray function.
For
var a = [ [1,2], [1,3] ];
console.log( jQuery.inArray([1,3],a ) )
I get -1 as ans. How to do this?
Thank you
In V8 (that is, Chrome), there is a nifty trick: while == does not work for arrays, <= && >= does.
You can iterate and check for each item if it's appearent:
for(var i = 0; i < a.length; i++) {
if(a[i] >= [1, 3] && a[i] <= [1, 3]) alert(i);
}
For other browsers, you'd need a function that checks for array equality:
http://www.svendtofte.com/code/usefull_prototypes/prototypes.js
Array.prototype.compareArrays = function(arr) {
if (this.length != arr.length) return false;
for (var i = 0; i < arr.length; i++) {
if (this[i].compareArrays) { //likely nested array
if (!this[i].compareArrays(arr[i])) return false;
else continue;
}
if (this[i] != arr[i]) return false;
}
return true;
}
Then:
for(var i = 0; i < a.length; i++) {
if(a[i].compareArrays([1, 3])) alert(i);
}
function inArray (needle, haystack) {
for (var idx in haystack) {
if (haystack[idx].join(',') == needle.join(','))
return idx;
}
return -1;
}
try this
function look4arr(arr, v) {
for (var i = 0, l = arr.length; i < l; i += 1) {
if (arr[i].toString() === v.toString()) { //or use +''
return true;
}
}
return false;
}
var a = [[1,2], 2],
ok = [1,2],
ko = [2,3]
look4arr(a, ok); // true
look4arr(a, ko); // false
// as far as the array you are looking at contains primitives seem to work fine
if you need to search for something "more" ...I mean object literals, regexp, functions
You could use a function similar to the following one
function look4x(arr, v) {
for (var i = 0, isObjOrArray = false, l = arr.length; i < l; i += 1) {
isObjOrArray = {}.toString.call(arr[i]).match(/\[object\s(Array|Object)\]/);
if (
(isObjOrArray && JSON.stringify(arr[i])+'' == JSON.stringify(v)+'' )
||
(!isObjOrArray && arr[i].toString() === v.toString())
) {
return true;//or i if a jQuery.inArray output is needed
}
}
return false; // or -1 ... if ... jQuery.inArray
}
var a = [
[1,[1,[1,[1,2]]]],
2,
true,
'hei',
Infinity,
{"o" : "s", 'd':[1,2,3]},
new RegExp(/\s/),
function(){alert('hei');}
],
ok = [1,[1,[1,[1,2]]]];
alert(
look4x(a, [1,[1,[1,[1,2]]]])
&&
look4x(a, true)
&&
look4x(a, 'hei')
&&
look4x(a, Infinity)
&&
look4x(a, {"o" : "s", 'd':[1,2,3]})
&&
look4x(a, new RegExp(/\s/))
&&
look4x(a, function(){alert('hei');})
); // true, in this case
Please note that I didn`t tested it yet with a complete test; I'll post a test asap
Event if I seem to be late, hope it can help someone.
Bye