Determining whether an array contains duplicate values - javascript

I would like to scan through a JS array and determine if all the elements are unique, or whether the array contains duplicates.
example :
my_array1 = [1, 2, 3]
my_array2 = [1, 1, 1]
I want get result like this :
my_array1 must be return true, because this array element is unique
and array2 must be return false, because this array element is not unique
How can I go about writing this method?

Sort your array first of all, and then go for a simple comparison loop.
function checkIfArrayIsUnique(arr) {
var myArray = arr.sort();
for (var i = 0; i < myArray.length; i++) {
if (myArray.indexOf(myArray[i]) !== myArray.lastIndexOf(myArray[i])) {
return false;
}
}
return true;
}

if you want to check for uniqueness you can also do this.As stated on the comment i do not assert this is as the only best option.There are some great answers down below.
var arr = [2,3,4,6,7,8,9];
var uniq = []; // we will use this to store the unique numbers found
// in the process for doing the comparison
var result = arr.slice(0).every(function(item, index, array){
if(uniq.indexOf(item) > -1){
// short circuit the loop
array.length=0; //(B)
return false;
}else{
uniq.push(item);
return true;
}
});
result --> true
arr.slice(0) creates a temporary copy of the array, on which the actual processing is done.This is because when the uniqueness criteria is met i clear the array (B) to short circuit the loop.This will make sure the processing stops as soon as the criteria is met.
And will be more nicer if we expose this as a method on a Array instance.
so we can do something like this [1,2,3,5,7].isUnique();
Add the following snippet and you are ready to go
Array.prototype.isUnique = function() {
var uniq = [];
var result = this.slice(0).every(function(item, index, arr) {
if (uniq.indexOf(item) > -1) {
arr.length = 0;
return false;
} else {
uniq.push(item);
return true;
}
});
return result;
};
arr.isUnique() --> true
DEMO

You may try like this:
function uniqueArray(arr) {
var hash = {}, result = [];
for ( var i = 0, l = arr.length; i < l; ++i ) {
if ( !hash.hasOwnProperty(arr[i]) ) {
hash[ arr[i] ] = true;
result.push(arr[i]);
}
}
return result;
}

try this :-
var my_array1 = [1, 2, 3]
var my_array2 = [1, 1, 1]
function isUnique(obj)
{
var unique=obj.filter(function(itm,i,a){
return i==a.indexOf(itm);
});
return unique.length == obj.length;
}
alert(isUnique(my_array1))
alert(isUnique(my_array2))
Demo

I think you can try with Underscore js , a powerful javascript library
Example the way to use underscore
function checkUniqueArr(arr){
var unique_arr = _.uniq(arr);
return arr.length == unique_arr.length;
}

The most efficient way to test uniqueness is:
function isUnique(arr) {
for(var i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) != i) return false;
}
return true;
}
This is O(n2) at worst case. At most time, it doesn't need to finish scanning for not-unique array.

function containsDuplicates(arr) {
var seen = {};
var duplicate = false;
for (var i = 0; i < arr.length; i++) {
if (seen[arr[i]]) {
duplicate = true;
break;
}
seen[arr[i]] = true;
}
return duplicate;
}
jsFiddle
Best-case: O(1) time and space - second element is the duplicate
Average/worst-case: O(n) time and space - no duplicates, or the duplicate is in the middle
Many of the answers here seem to be relying on some complex interspersion of array methods, which are inherently iterative, and generally don't seem appropriate for this fairly simple task. Algorithmically, this problem can be solved in O(n) time, but any nesting of indexOf/filter/map (or similar array methods) in a for loop means that your computation time will grow (at best) quadratically with your array size, rather than linearly. This is inefficient in time.
Now, in general, micro-optimization really is not necessary unless you have identified this to be a performance bottleneck in your application. But this kind of algorithm, in my opinion, is something you design (in pseudocode) and match to your application's needs before you even start coding. If you will have a huge data-set in your array, you will probably appreciate not having to look through it several times to get your answer. Of course, the caveat here is that you're trading time complexity for space complexity, since my solution requires O(n) space for caching previously seen values.

If you need to check all element are unique then following will do the trick
<script>
my_array1 = [11, 20, 3]
my_array2 = [11, 11, 11]
var sorted1= my_array1.sort();
var sorted2= my_array2.sort();
if(sorted1[0]==sorted1[sorted1.length-1])
alert('all same');
if(sorted2[0]==sorted2[sorted2.length-1])
alert('all same');
</script>

I just came up with this answer.
I'm preparing for an interview.
I think this is rock solid.
let r = [1,9,2,3,8];
let r2 = [9,3,6,3,8];
let isThereDuplicates= r.slice().sort().some((item,index,ar)=>(item ===ar[index+1]));
console.log('r is: ',isThereDuplicates) // -> false. All numbers are unique
isThereDuplicates= r2.slice().sort().some((item,index,ar)=>(item ===ar[index+1]));
console.log('r2 is: ',isThereDuplicates) //->true. 3 is duplicated
I first slice and sort without mutating the original array.
r.slice().sort()
Then I check that for at least one item, item is equal to the next item on the array.
.some((item,index,array)=>
item === array[index+1]
);

Related

Fastest way to repeat an array in Javascript

I have been trying to figure out a fast way of creating an array based on repeating an element a given number of times. For my purposes, generally the element I'd be repeating is another array, and I'd be making a long repeated (2-dimensional) array out of it, so I'd prefer it to be fast. Note that in each example, c=[element] since that's how it naturally occurs in my code.
There are a few options here that I've found. At most basic is option 1:
function repeatSimple(c, n) {
var arr = [];
for (var i=0; i<n; i++) {
arr = arr.concat(c);
};
return arr;
};
Then from this question (Concatenate array to itself in order to duplicate it), gdbdmdb has another option:
function repeatApply(c, n) {
return [].concat.apply([], Array.apply(0, Array(n)).map(function() { return c }));
};
My thinking was (a) I don't really understand the second option well enough to know whether it's a good solution, and (b) it seems silly to have to call concat a whopping n times as in the first option. So I came up with one more:
function repeatBinary(c, n) {
var arr = [];
var r = 0;
while (n>0) {
r = n%2;
if (r>0) {
arr = arr.concat(c);
};
n = (n-r)/2;
if (n>0) {
c = c.concat(c);
};
};
return arr
};
This way, I only have to call concat at most 2log_2(n) times.
So, my question is, what is the fastest way to do this? Is it one of the options I'm looking at here or is there something else that blows them out of the water? Or will all of these options work at such similar speeds that it really doesn't make a difference?
I think the fastest way to do this witout even using the concat function :
function repeatSimple(element, times)
{
var result = [];
for(var i=0;i<times;i++)
result.push(element);
return result;
}
And if you don't want to use the push function , you can assign the value directly to the item on the array like this
function repeatSimple(element, times)
{
var result = Array(times);
for(var i=0;i<times;i++)
result[i] = element;
return result;
}
Another clever way to do this is to join an array and split it like this
function repeatSimple(element, times)
{
(result = Array(times).join("," + element).split(',')).shift()
return result;
}
But this last function returns an array of strings, you have to convert every element to the type you need, but anyway, these functions may help you

Remove array element when subarray has certain values

I have an array that contains any number of subarrays, each containing exactly two values.
i.e: interestArray[[1, 5], [3, 8] ... ]
How do I remove say the subarray containing the values [3, 8]?
My code is:
$('td', container).click(function(){
if(!$(this).hasClass('purchased') && !$(this).hasClass('manu'))
{
var manuId = $(this).parent().children('td:first-child').data('manu-id');
var typeId = $(this).data('type-id');
if($(this).hasClass('interest'))
{
$(this).removeClass('interest');
$(this).parent().children('td.manu').removeClass('interest');
var index = interestArray.indexOf([manuId, typeId]);
interestArray.splice(index, 1);
} else {
$(this).addClass('interest');
$(this).parent().children('td.manu').addClass('interest');
interestArray.push([manuId, typeId]);
}
//updateSurvey(interestsArray);
console.log(interestArray)
}
})
The below section does not work, and simply removes the first subarray.
var index = interestArray.indexOf([manuId, typeId]);
interestArray.splice(index, 1);
Here's a generic approach with your requirements:
var arr = [[1,2],[3,4],[5,6]];
var remove = [3,4];
for (var i=0; i<arr.length; i++) {
if (arr[i][0] == remove[0] && arr[i][1] == remove[1]) {
arr.splice(i, 1);
break;
}
}
console.log(arr); //=> [[1,2],[5,6]]
For a general approach, you can filter the array:
var reducedArray = interestArray.filter(function (item) {
return item[0] != manuId || item[1] != typeId;
});
You cannot use indexOf because that looks for the identical object (not merely an equivalent one).
If you're running an earlier version of JS that doesn't have Array.filter, there's a nice shim on the filter doc page linked to above.
Here is my personal solution more complete to avoid multiple entry issue and the break; thing seen above, it also avoids an issue if the array is after entry removal (it is jquery based but you can make a regular loop if you feel more comfy with it):
$.each( answers, function( index, value ){
if (typeof answers[index] != "undefined")
{
if(answers[index]["question_id"]==answer_to_del)
{
delete answers[index];
}
}
});
//Clean answer array from empty values created above
answers = answers.filter(function(n){ return n != undefined });

Only return values found in all arrays

Simple question, but i dont know how to solve it
I have several arrays, but i only want the values that all arrays have in common
Im using javascript.
Try looking for the value in each of the arrays using indexOF.
I never knew IE didn't support indexOf, but here's a quick fix from this post.
Something like this should work:
function getCommonElements() {
var common = [],
i, j;
if (arguments.length === 0)
return common;
outerLoop:
for (i = 0; i < arguments[0].length; i++) {
for (j = 1; j < arguments.length; j++)
if (-1 === arguments[j].indexOf(arguments[0][i]))
continue outerLoop;
common.push(arguments[0][i]);
}
return common;
}
Call it with any number of arrays as arguments:
var commonEls = getCommonElements(arr1, arr2, arr3, etc);
In case it's not obvious, the idea is to loop through the array from the first argument and test each of its elements against the other arrays. As soon as a particular element is found to not be in any of the other arrays from the other arguments continue on with the next element. Otherwise add the current element to the output array, common.
If you need to support browsers (IE < 9) that don't support the Array.indexOf() method you can either include the shim shown at the MDN page or replace the .indexOf() test from my code with another loop.
I think this should work.
var arr1 = [1,2,3,4]
, arr2 = [2,3,4,5]
, arr3 = [3,4,5,6]
, arrs = [arr1, arr2, arr3];
var all = arr1.concat(arr2.concat(arr3)).sort()
, red1 = all.filter(
function(val, i, arr) {
return i === arr.lastIndexOf(val)-1;
})
, red2 = red1.filter(
function(val, i, arr) {
var shared = true;
arrs.forEach(
function(arr, i, src) {
if (arr.indexOf(val) === -1)
shared = false;
})
return shared;
})
If you are only concerned with modern browsers that support reduce(), then use this solution:
Finding matches between multiple JavaScript Arrays
If you must support IE6, then use my solution below. Here's how I got this to work in IE6 using jQuery:
// Find common values across all arrays in 'a',
// where 'a' is an array of arrays [[arr1], [arr2], ...]
Object.common = function(a) {
var aCommon = [];
for (var i=0,imax=a[0].length,nMatch,sVal; i<imax; i++) {
nMatch = 0;
sVal = a[0][i];
for (var j=1,jmax=a.length; j<jmax; j++) {
nMatch += ($.inArray(sVal, a[j])>-1) ? 1 : 0;
}
if (nMatch===a.length-1) aCommon.push(sVal);
}
return aCommon;
}
Basically, you just loop through each value of the first array in 'a' to see if it exists in the other arrays. If it exists, you increment nMatch, and after scanning the other arrays you add the value to the aCommon array if nMatch equals the total number of the other arrays.
Using the sample data provided by Florian Salihovic, Object.common(arrs) would return [3, 4].
If you cannot use jQuery, then replace $.inArray() with the code provided by Mozilla:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/IndexOf

Removing duplicates from an array in Javascript [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 8 years ago.
var data = localStorage.getItem('oldData').split(" ");
I am accessing localStorage as above and getting an array of values. Some of the elements are repeated in the string value for oldData, for example:
apples oranges apples apples
I want data to have only two elements apples and oranges. How can I do this in Javascript?
Array.prototype.unique = function(){
return Object.keys(this.reduce(function(r,v){
return r[v]=1,r;
},{}));
}
Strap it on. It's O(n) because using an object just requires you to loop through the array once and assign every value in it as a key, overwriting as you go. This only works when the values are primitives (or you have Harmony WeakMaps). But that's almost always the kind of array you want to do this one so it works out.
For bonus points here's the second best way to do it. This is at minimum twice as fast as the normal double loop answers and is at minimum as good as the ones requiring presorting,
(but still worse than the above hash method which is infinitely faster).
Array.prototype.unique = function(){
return this.filter(function(s, i, a){
return i == a.lastIndexOf(s);
});
}
The reason it beats every other answer aside from the hash is because it's able to get the benefit of sorting without doing the sorting step. It only searches from the current item forward, and from the other end in reverse, so there will never be a case where two items are checked against each other twice, and there will never be an unnecessary comparison done because it always quits at the very minimum amount of work needed to make a final decision. And it does all of this with the minimum possible creation of placeholder variables as a bonus.
first is to insert one value in your array by using push
var array = [];
array.push("newvalue");
then the next insertion of value, check if your value is existing in your array using "for loop". then if the value does not exist, insert that value using push() again
Array.prototype.unique = function()
{
var a = [];
var l = this.length;
for(var i=0; i<l; i++)
{
for(var j=i+1; j<l; j++)
{ if (this[i] === this[j]) j = ++i; }
a.push(this[i]);
}
return a;
};
Something like this should do the trick:
uniqueValues = function(array) {
var i, value,
l = array.length
set = {},
copy = [];
for (i=0; i<l; ++i) {
set[array[i]] = true;
}
for (value in set) {
if (set.hasOwnProperty(value)) {
copy.push(value);
}
}
return copy;
}
This is what I have used finally
var data = localStorage.getItem('oldData').split(" ");
var sdata = data.sort();
var udata = [];
var j = 0;
udata.push(sdata[0]);
for (var i = 1; i < data.length - 1; i += 1) {
if (sdata[i] != udata[j]) {
udata.push(sdata[i]);
j++;
}
}

Get first element of a sparse JavaScript array

I have an array of objects in javascript. I use jquery.
How do i get the first element in the array? I cant use the array index - as I assign each elements index when I am adding the objects to the array. So the indexes arent 0, 1, 2 etc.
Just need to get the first element of the array?
If you don't use sequentially numbered elements, you'll have to loop through until you hit the first one:
var firstIndex = 0;
while (firstIndex < myarray.length && myarray[firstIndex] === undefined) {
firstIndex++;
}
if (firstIndex < myarray.length) {
var firstElement = myarray[firstIndex];
} else {
// no elements.
}
or some equivalently silly construction. This gets you the first item's index, which you might or might not care about it.
If this is something you need to do often, you should keep a lookaside reference to the current first valid index, so this becomes an O(1) operation instead of O(n) every time. If you're frequently needing to iterate through a truly sparse array, consider another data structure, like keeping an object alongside it that back-maps ordinal results to indexes, or something that fits your data.
The filter method works with sparse arrays.
var first = array.filter(x => true)[0];
Have you considered:
function getFirstIndex(array){
var result;
if(array instanceof Array){
for(var i in array){
result = i;
break;
}
} else {
return null;
}
return result;
}
?
And as a way to get the last element in the array:
function getLastIndex(array){
var result;
if(array instanceof Array){
result = array.push("");
array.pop;
}
} else {
return null;
}
return result;
}
Neither of these uses jquery.
Object.keys(array)[0] returns the index (in String form) of the first element in the sparse array.
var array = [];
array[2] = true;
array[5] = undefined;
var keys = Object.keys(array); // => ["2", "5"]
var first = Number(keys[0]); // => 2
var last = Number(keys[keys.length - 1]); // => 5
I was also facing a similar problem and was surprised that no one has considered the following:
var testArray = [];
testArray [1245]= 31;
testArray[2045] = 45;
for(index in testArray){
console.log(index+','+testArray[index])
}
The above will produce
1245,31
2045,45
If needed you could exist after the first iteration if all that was required but generally we need to know where in the array to begin.
This is a proposal with ES5 method with Array#some.
The code gets the first nonsparse element and the index. The iteration stops immediately with returning true in the callback:
var a = [, , 22, 33],
value,
index;
a.some(function (v, i) {
value = v;
index = i;
return true;
});
console.log(index, value);
If you find yourself needing to do manipulation of arrays a lot, you might be interested in the Underscore library. It provides utility methods for manipulating arrays, for example compact:
var yourArray = [];
yourArray[10] = "foo";
var firstValue = _.compact(yourArray)[0];
However, it does sound like you are doing something strange when you are constructing your array. Perhaps Array.push would help you out?

Categories