Search 2d javascript array for a known complete array - javascript

I have a 2d array similar to this:
var array = [
{100,200},
{200,200},
{100,400}
];
Now I want to find if a known array exists inside the 2d array. For example, I want to check if [200,200] exists as a 2nd level array inside the 2d array.
On 1d arrays in the past I've used something like:
if (value in array) {...}
Can't seem to get that method working on 2d. What is the best solution?

Not sure if you already know but your syntax is not correct. It should look like this:
var array = [
[100,200],
[200,200],
[100,400]
];
A naive way to check if [200, 200] exists as a 2nd level array:
console.log(array[1][0] == 200 && array[1][1] == 200);
Another naive approach is to use a nested loop and go through each item.
If you want a fast approach to this, you might want to read up on search algorithms.
Searching Algorithms

var array = [
[100,200],
[200,200],
[100,400]
];
var searchFor = [200,200];
function arrayExistsInside(haystack, needle) {
for(var i = 0; i < haystack.length; i++) {
if(compareArray(haystack[i], needle)) return true;
}
return false;
}
function compareArray(array1, array2) {
if(array1.length != array2.length) return false;
for(var i = 0; i < array1.length; i++) {
if(array1[i] != array2[i]) return false;
}
return true;
}
if(arrayExistsInside(array, searchFor)) { ... }
You could also use the compare function outlined on How to compare arrays in JavaScript?

Related

Determining whether an array contains duplicate values

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]
);

forEach works - why not for loop?

I'm working on the flatten kata at codewars.com - my code closely resembles a solution I've found, so I feel like my logic is on the right track. But I can't seem to get my code to work and I don't know if it's a dumb syntax error or if I'm doing something fundamentally incorrect.
Instructions:
Write a function that flattens an Array of Array objects into a flat Array. Your function
must only do one level of flattening.
flatten([[1,2,3],["a","b","c"],[1,2,3]]) // => [1,2,3,"a","b","c",1,2,3]
Working solution using forEach:
var flatten = function (lol){
var res = [];
lol.forEach(function (x) {
if (x instanceof Array)
res = res.concat(x);
else
res.push(x);
});
return res;
}
My code using for loops:
var flatten = function (array){
var newArray = [];
for (i = 0; i < array.length; i++) {
if (i instanceof Array)
for (e = 0; e < i.length; e++) {
newArray.push(e);
}
else
newArray.push(i);
}
return newArray;
}
The most important reason why it isn't working is that you are treating your indices (i and e) as if they were the actual array elements (hence, the sub Arrays themselves). i is not the actual array, and does not have any array properties. It is just a number.
Each element must be referenced via the array[index], so in the case of the array argument, in the top loop, you would check array[i], but most importantly, if it is not an array, that is what you would push().
In your inner loop, you face a similar issue with e. However, you cannot simply do array[e] as the array you would be looking at would be array[i]. The proper way to address this is to make another variable for the array OR simply array[i][e]. Again, this is the value you would push().
I understand that this answer is a little vague, but it is intentionally so, as this is obviously an assignment from which you are trying to learn.
You need to use the value of the original array to push/concat into the new one. Also, you don't need to check the type, you can just concat everything:
var flatten = function (array) {
var newArray = [];
var arrayLength = array.length;
for (i = 0; i < arrayLength; i++) {
newArray = newArray.concat(array[i]);
}
return newArray;
}
if (array[i] instanceof Array)
Your algorithm looks fine, but you are referencing a Number index where you mean to be referencing an array element. Fix this in 3 places and your code should work.
Spoiler:
var flatten = function (array){
var newArray = [];
for (i = 0; i < array.length; i++) {
if (array[i] instanceof Array)
newArray = newArray.concat(array[i]);
else
newArray.push(array[i]);
}
return newArray;
}

Search an associate array / hash in Javascript [duplicate]

This question already has answers here:
Finding matching objects in an array of objects?
(5 answers)
Closed 9 years ago.
I have an array that looks like this
var data = [
{"target": "production", "datapoints": [[165.0, 136], [141.0, 176], [null, 176]]},
{"target": "test", "datapoints": [[169.0, 100], [151.0, 160], [null, 120]]},
{"target": "backup", "datapoints": [[1.0, 130], [32.0, 120], [13.0, 130]]}
]
Is it possible to search this array to return the hash that contains for example "production"
{"target": "production", "datapoints": [[165.0, 136], [141.0, 176], [null, 176]]}
I looked at this http://api.jquery.com/jQuery.inArray/ but didn't know how to use it.
You can do:
var target = "production";
var result = $.grep(data, function(e){ return e.target == target; });
console.log(result);
Not sure if this is what you meant, but try this:
for(var i=0;i<data.length;i++)
if(data[i].target=='production')
return data[i]
// or do something else/more
This will iterate over the array and check the 'target' attribute for the value 'production'
You've mentioned associative arrays, so be it
In case you're doing a one time read (later modifications are allowed) and many time search over this data, it is much more sufficient to actually translate your array to Javascript object (becoming an associative array):
var assocArray = {};
for(var i = 0; i < data.length; i++)
{
assocArray[data[i].target] = data[i];
}
and then searching for
assocArray[name]
would have O(1) complexity while looping over the array each time has O(n/2) => O(n). This would significantly speed up searches over this data. But this only makes sense when data is read once and searched many times. New hashes/targets can of course be added later or existing ones changed as well.
So in your case you would then simply get your production by
assocArray["production"]
and you'd get the whole object associated with this hash/target.
Note: This only works if you have unique hash/target names. Whenever you have several objects with the same hash/target the last one would be returned. Following is a solution when you have several objects in your array that have the same target/hash.
Multiple results per hash/target
In case you do have several objects, that have the same hash/target, your array to object conversion should be changed a bit.
var assocArray = {};
for(var i = 0; i < data.length; i++)
{
// doesn't exist? create array
if (!assocArray[data[i].target])
{
assocArray[data[i].target] = [];
}
// push an element
assocArray[data[i].target].push(data[i]);
}
This will make an associative array (Javascript object) that consistently returns an array of elements with one or more objects. It makes later manipulation easier because in either case an Array is being returned. But it could easily be changed that on a single result it should just return an object an not an array with a single element.
function findHash(hash, data) {
var dataLen = data.length;
for(dataLen > 0; dataLen--;) {
if( data[dataLen].target == hash) {
return data[dataLen];
}
}
return false;
}
I don't recommend using this on large arrays but it should work for you or get you on the right track.
Try this function:
var getDataByTarget = function (target) {
var ret = false;
$.each(data, function () {
if (this.target == target) {
ret = this;
return false;
}
});
return ret;
};
Fiddle: http://jsfiddle.net/vUEYA/

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

jQuery/Javascript if value is in array, continue

I have data that is in an array, these are the ID's for users that have commented on said post. I want to compare this array with the id of the user, and if their id is in this array, continue with the code.
my array looks like:
({0:"1", 3:"6"}) // 1 and 6 are the ID's that I want to work with.
So I want to do something like:
var array = ({0:"1", 3:"6"});
var userID = 6;
if(in(array)==userID)
{
///you are in the list, so do whatever
}
Instancing your array like that will not create an array, but an object. Normally, you instantiate arrays in javascript like this:
var arr = [17, 4711];
Checking for a value using Array.indexOf:
arr.indexOf(17); // => 0
arr.indexOf(4711); // => 1
arr.indexOf(42); // => -1
Pushing:
arr.push(42);
arr.indexOf(42); // => 2
Array.indexOf is not in IE < 9, so I suggest you look into using a shim.
function inArray(needle, haystack) {
var count = 0;
for (var k in haystack) {
if (haystack.hasOwnProperty(k)) {
++count;
}
}
for (var i in haystack) {
if(haystack[i] == needle) return true;
}
return false;
}
​
See : http://jsfiddle.net/ryN6U/1/
If will not work with your object :)
You can loop through your object and check it against your userid. Something like
$(document).ready(function(){
var myArray = ({0:"1", 3:"6"});
var userId = 6;
for(vals in myArray){
if(userId == myArray[vals]){
alert("userid exists in array");
}
}
});
When testing against an array I would use jQuery's inArray()
if your looking for the first item in an object with a certain value look at this thread
json index of property value

Categories