Faster code for checking repeated values in a JS array - javascript

var valueArray = ['ABC','DEF','GHI','ABC','JKL','MNO','DEF'];
var flag =false;
for(var i=0; i<valueArray.length; i++)
{
for(var j=0; j<valueArray.length; j++)
{
if(valueArray[j] == valueArray[i] && j != i)
{
flag = true;
break;
}
}
}
if(flag)
alert('same values found');
I am trying to validate one array by checking for duplicate values, i used above code, i don't think its a better way. is there any ways with jquery for this or some good js codes for it.

Not sure about jquery, but performance will be better with just one for loop:
for(var i = 0; i < valueArray.length; i++)
{
if (valueArray.indexOf(valueArray[i], i+1) != -1) {
flag = true;
break;
}
}
jsPerf test: http://jsperf.com/check-for-double-occurences

If you want a fast, compatible, "works everywhere" function that just checks for duplicates and doesn't require any library, consider:
function hasDups(arr) {
// Firstly copy array so don't affect original, then sort
var t = arr.slice().sort();
// If adjacent members have the same value, return true
for (var i=1, iLen=t.length; i<iLen; i++) {
if (t[i] === t[i-1]) return true;
}
return false;
}
console.log(hasDups(['abc','dvf','abc'])); // true
However you might want something a little more functional, e.g. that you can provide a compare function to so that, say, 'abc' == 'ABC' or '5' == 5.
Or if you want to use new features and avoid the copy and sort, consider:
function hasDups2(arr) {
var obj = {};
return arr.some(function(v){
if (obj.hasOwnProperty(v)) return true;
obj[v] = '';
});
}
The same strategy can be applied to the first as well and avoid ES5's some.
Note that both the above are only really suitable for comparing primitive values, though the first is better for that. If you want a reliable function to look for duplicate objects, that requires a bit more work.

Use jquery.unique() and compare the array size. If the size of the resultant array is not the same then return false.
Doc for jquery.unique()

Related

Why this works(JavaScript)?

I was working on one of my projects and had to check if any of the coordinates in two arrays(of the same length) at the same index are the exact same or not. I know there are few methods to do this but I came across one that started to rise my curiosity. Why does it work?
So here is a syntax -
exports.check = (arr1, arr2) => {
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return true; //If none of the points are the same
}return false; //If some of the points are the same
}
By my knowledge return statement should stop/break the loop and return the first value in any case. True or not. But it does not... Can someone explain what am I missing here?
You are probably confused with the way the if block is appearing. You can avoid brackets if the result after an if check is a one-liner. It does return true only and only when there is not a match.
This:
exports.check = (arr1, arr2) => {
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return true; //If none of the points are the same
}return false; //If some of the points are the same
}
is the same as:
exports.check = (arr1, arr2) => {
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i]) {
return true;
}
}
return false;
}
P.S: The comments in your code are wrong and the code as well. This is just to explain the about the if block
It might be easier to understand if presented thus:
//returns true if arrays differ or false if arrays are same
exports.arraysAreDifferent = (arr1, arr2) =>
{
for(var i = arr1.length; i>=0; i--) {
if(arr1[i] !== arr2[i]){
return true; //if even one pair of array values differ, arrays are different
} else {
//do nothing/check next pair
}
}
return false; //Loop finished without finding difference. Arrays are same
}
The comments were a bit misleading, and the indentation/bracketing/putting return false after the girly bracket that closed the loop might have been a confusing read that made it look like it was "if x then return this else return that" so you may have pondered how would the loop run to completion. It runs because there is no else; if the if test always fails the loop runs through every pair

Fast way to check if a javascript array is binary (contains only 0 and 1)

What is a quick way to determine if an array is only composed of 0's and 1's?
I'm vaguely familiar with a boolean solution but am not away how to implement it. In order to implement is you would have to assign values to the boolean
true = 0
and
false = 1
But how would you implement this if you are given an array such that
array = [1,1,1,1,0,0,0,0]
isArrayBool (){
}
Very very naive solution:
function isArrayBool(array) {
for (var i of array) {
if (i !== 0 && i !== 1) return false;
}
return true;
}
console.log(isArrayBool([1,0,0,0,1])); // true
console.log(isArrayBool([1])); // true
console.log(isArrayBool([2,3,0])); // false
So I threw a few functions together in jsperf to test. The fastest one I found so far is the one below (which is much faster than the for of version):
function isBoolFor(arr) {
for(var i=arr.length-1; i>=0; --i){
if(arr[i] !== 0 && arr[i] !== 1) return false
}
return true
}
Comparison is here
EDIT: I played around with another version that turned out to be quicker:
function isBoolFor(arr) {
for(var i=0; arr[i] === 0 || arr[i] === 1; i++){}
return i === arr.length
}
The key here is that because most of the array you are checking will consist of zeros and ones, you can avoid doing two boolean checks every iteration by using the || instead of the && negative check. It is only a subtle improvement, and could be argued to be no better than the one above in practicality.
UPDATE: So the difference between all the for and while variants is too subtle to declare an overall winner. So in that case I would go for readability. If you want binary use typed arrays!
FINAL UPDATE:
I was curious and wanted to find an even faster version, and it can be done if the array is known to be only numbers. If the array contains only numbers, then you can use a bitwise operator check for either of the values in question. For example:
function isBoolFor(arr) {
const test = ~0x01
for(var i=arr.length-1; i>=0; --i){
if(test & arr[i]){ return false }
}
return true
}
https://jsperf.com/bool-array-test-2/1
As we can see here, the fastest way to do this can be seen here... With a simple for loop, as suggested by user Jaromanda in a comment. This for loop blows other solutions out of the water in terms of speed.
var someArray = [1,0,1,1,1,1,0,0,1,0,1,0,0,1,0,1,0,1,1,1,1,0,1,1,0,1,0];
function simpleForLoop(array){
var numArgs = someArray.length;
for(var loop = 0; loop < numArgs; loop++){
var arg = someArray[loop];
if(arg !== 0 && arg !== 1){ return false; }
}
return true;
}
var isbool = simpleForLoop(someArray);

Replace multiple string items in the array

I have an array that shows this value "135_1,undefined,undefined"
I have to find the "undefined" in the above array and then replace it with "0_0".Undefined can occur multiple times in the array.
I used
var extra = myVariable.replace("undefined", "0_0");
alert(extra);
but then I have to use this three times so that every single time it can search one and replace it.
I have also used this::
for (var i = 0; i < myVariable.length; i++) {
alert(myVariable[i]);
myVariable[i] = myVariable[i].replace(/undefined/g, '0_0');
}
alert(myVariable);
but it did'nt solved my purpose.
String.prototype.replace is a method accessible to strings. undefined is not a string.
This might help you.
for (var i=0, len=arr.length; i<len; i++) {
if (arr[i] === undefined) {
arr[i] = "0_0";
}
}
alert(JSON.stringify(arr));
You could also use Array.prototype.map for this. Note, it only works in IE >= 9
arr = arr.map(function(elem) {
return elem === undefined ? "0_0" : elem;
});
Since the question is tagged with jquery you can use $.map():
var extra = $.map(myVariable, function(item) {
return item || '0_0';
}
This will return a new array whereby each item comprising (in your case) an empty string or undefined is replaced by '0_0'.
var arr = ['135_1',undefined,undefined];
while(arr.indexOf(undefined) != -1) {
pos=arr.indexOf(undefined);
arr[pos]='0_0';
}

Change a particular object in an array

Starting with an array of objects:
var array=[
{name:"name1",value:"value1"},
{name:"nameToChange",value:"oldValue"},
{name:"name3",value:"value3"}
];
How do change the value of a given property of one of the objects when another given property in the object is set to a given value?
For instance, starting with my array shown above, I wish to change value to "newValue" when name is equal to "nameToChange".
var array=[
{name:"name1",value:"value1"},
{name:"nameToChange",value:"newValue"},
{name:"name3",value:"value3"}
];
PS. To create the initial array, I am using jQuery's serializeArray(), and I do not wish to change the value of <input name="nameToChange">. I suppose I can change its value, use serialArray(), and then change it back, but this sounds more complicated than necessary.
The easiest way is to iterate over this array:
var i = arr.length;
while (i--) {
if (arr[i].name === 'nameToChange') {
arr[i].value = 'newValue';
break;
}
}
You won't be able to do the same stuff with native 'indexOf', as objects are to be compared.
for (var i = 0; i < array.length; i++) {
if (array[i].name == 'nameToChange') {
array[i].value = 'value';
break;
}
}
fiddle Demo
You need to go through all the elements and search for the required one and then replace with the value.
for(var i = 0; i < array.length; i++){
if(array[i]["name"] == str) {
array[i]["value"] = newValue;
break;
}
}
It's 2013; skip all the messy for loops and use forEach. It's much simpler and semantically cleaner:
array.forEach(function (e) {
if (e.name == 'nameToChange')
e.value = 'newValue';
})
Since you are using jQuery, you could use this:
$.each(array, function () {
if(this.name == 'nameToChange') this.value = 'value';
});
Fiddle

Three map implementations in javascript. Which one is better?

I wrote a simple map implementation for some task. Then, out of curiosity, I wrote two more. I like map1 but the code is kinda hard to read. If somebody is interested, I'd appreciate a simple code review.
Which one is better? Do you know some other way to implement this in javascript?
var map = function(arr, func) {
var newarr = [];
for (var i = 0; i < arr.length; i++) {
newarr[i] = func(arr[i]);
}
return newarr;
};
var map1 = function(arr, func) {
if (arr.length === 0) return [];
return [func(arr[0])].concat(funcmap(arr.slice(1), func));
};
var map2 = function(arr, func) {
var iter = function(result, i) {
if (i === arr.length) return result;
result.push(func(arr[i]));
return iter(result, i+1);
};
return iter([], 0);
};
Thanks!
EDIT
I am thinking about such function in general.
For example, right now I am going to use it to iterate like this:
map(['class1', 'class2', 'class3'], function(cls) {
el.removeClass(cls);
});
or
ids = map(elements, extract_id);
/* elements is a collection of html elements,
extract_id is a func that extracts id from innerHTML */
What about the map implementation used natively on Firefox and SpiderMonkey, I think it's very straight forward:
if (!Array.prototype.map) {
Array.prototype.map = function(fun /*, thisp*/) {
var len = this.length >>> 0; // make sure length is a positive number
if (typeof fun != "function") // make sure the first argument is a function
throw new TypeError();
var res = new Array(len); // initialize the resulting array
var thisp = arguments[1]; // an optional 'context' argument
for (var i = 0; i < len; i++) {
if (i in this)
res[i] = fun.call(thisp, this[i], i, this); // fill the resulting array
}
return res;
};
}
If you don't want to extend the Array.prototype, declare it as a normal function expression.
As a reference, map is implemented as following in jQuery
map: function( elems, callback ) {
var ret = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
var value = callback( elems[ i ], i );
if ( value != null )
ret[ ret.length ] = value;
}
return ret.concat.apply( [], ret );
}
which seems most similar to your first implementation. I'd say the first one is preferred as it is the simplest to read and understand. But if performance is your concern, profile them.
I think that depends on what you want map to do when func might change the array. I would tend to err on the side of simplicity and sample length once.
You can always specify the output size as in
var map = function(arr, func) {
var n = arr.length & 0x7fffffff; // Make sure n is a non-neg integer
var newarr = new Array(n); // Preallocate array size
var USELESS = {};
for (var i = 0; i < n; ++i) {
newarr[i] = func.call(USELESS, arr[i]);
}
return newarr;
};
I used the func.call() form instead of just func(...) instead since I dislike calling user supplied code without specifying what 'this' is, but YMMV.
This first one is most appropriate. Recursing one level for every array item may make sense in a functional language, but in a procedural language without tail-call optimisation it's insane.
However, there is already a map function on Array: it is defined by ECMA-262 Fifth Edition and, as a built-in function, is going to be the optimal choice. Use that:
alert([1,2,3].map(function(n) { return n+3; })); // 4,5,6
The only problem is that Fifth Edition isn't supported by all current browsers: in particular, the Array extensions are not present in IE. But you can fix that with a little remedial work on the Array prototype:
if (!Array.prototype.map) {
Array.prototype.map= function(fn, that) {
var result= new Array(this.length);
for (var i= 0; i<this.length; i++)
if (i in this)
result[i]= fn.call(that, this[i], i, this);
return result;
};
}
This version, as per the ECMA standard, allows an optional object to be passed in to bind to this in the function call, and skips over any missing values (it's legal in JavaScript to have a list of length 3 where there is no second item).
There's something wrong in second method. 'funcmap' shouldn't be changed to 'map1'?
If so - this method loses, as concat() method is expensive - creates new array from given ones, so has to allocate extra memory and execute in O(array1.length + array2.length).
I like your first implementation best - it's definitely easiest to understand and seems quick in execution to me. No extra declaration (like in third way), extra function calls - just one for loop and array.length assignments.
I'd say the first one wins on simplicity (and immediate understandability); performance will be highly dependent on what the engine at hand optimizes, so you'd have to profile in the engines you want to support.

Categories

Resources