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/
Related
I have an situation where I have 3 different arrays with very different amounts of objects in it. I've read many questions and blog posts about this but Im still unsure when to use what.
PS! My biggest problem is that I need to iterate and push (perfect for arrays), also find if exists in array and delete (more suitable for objects). Specific order is not required.
I can't allow having same object in both array1 and array1clicked
because they should perform different actions.
When it's best to use object and when array in my example? What should I replace with object and what should stay as array? Im pretty sure that amounts of objects in it also matters, right?
My current code:
//Objects in arrays are literally custom {objects} with custom prototypes and html
var array1 = [ 20 objects ];
var array1clicked = [];
var array2 = [ 250 objects ];
var array2clicked = [];
var array3 = [ 50 000 objects ];
var array3clicked = [];
//Each object in arrays has event attached
objecthtml.click(function() {
//Add to clicked array
array1clicked.push(thisobject);
//Remove from initial array
var index = array1.indexOf(thisobject);
if (index > -1) {
array1.splice(index, 1);
}
}
//Same with array2 and array3 objects
//Iterations on different conditions
var array1count = array1.length;
var array1clickedcount = array1clicked.length;
//Same with array2 and array3
if(condition1) {
for(a = 0; a < array1count; a++) {
array1[a].div.style.visibility = 'hidden';
}
//Same with array2 and array3 objects
for(a = 0; a < array1clickedcount; a++) {
array1clicked[a].div.style.visibility = 'visible';
}
//Same with array2clicked and array3clicked objects
}
else if(condition2) {
for(a = 0; a < array1count; a++) {
array1[a].div.style.visibility = 'visible';
}
//Same with array2 and array3 objects
for(a = 0; a < array1clickedcount; a++) {
array1clicked[a].div.style.visibility = 'hidden';
}
//Same with array2clicked and array3clicked objects
}
It seems you want a data structure with these operations:
Iteration
Insert
Delete
Search
With arrays, the problem is that searches and deletions (with reindexing) are slow.
With objects, the problem is that the property names can only be strings.
The perfect structure is a set.
var s = new Set();
s.add(123); // insert
s.has(123); // search
s.delete(123); // delete
s.values(); // iterator
In your case, I think you have to use just Array.
In common case, you could use object to keep references and push some values into it, but If you wanna iterate on this, I think you have to use Array.
I have an array of objects which contain certain duplicate properties: Following is the array sample:
var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
So what i need is to merge the objects with same values of x like the following array:
var jsonData = [{x:12, machine1:7, machine2:8}, {x:15, machine2:7}]
I like the lodash library.
https://lodash.com/docs#groupBy
_.groupBy(jsonData, 'x') produces:
12: [ {x=12, machine1=7}, {x=12, machine2=8} ],
15: [ {x=15, machine2=7} ]
your desired result is achieved like this:
var jsonData = [{x:12, machine1: 7}, {x:15, machine2:7},{x:12, machine2: 8}];
var groupedByX = _.groupBy(jsonData, 'x');
var result = [];
_.forEach(groupedByX, function(value, key){
var obj = {};
for(var i=0; i<value.length; i++) {
_.defaults(obj, value[i]);
}
result.push(obj);
});
I'm not sure if you're looking for pure JavaScript, but if you are, here's one solution. It's a bit heavy on nesting, but it gets the job done.
// Loop through all objects in the array
for (var i = 0; i < jsonData.length; i++) {
// Loop through all of the objects beyond i
// Don't increment automatically; we will do this later
for (var j = i+1; j < jsonData.length; ) {
// Check if our x values are a match
if (jsonData[i].x == jsonData[j].x) {
// Loop through all of the keys in our matching object
for (var key in jsonData[j]) {
// Ensure the key actually belongs to the object
// This is to avoid any prototype inheritance problems
if (jsonData[j].hasOwnProperty(key)) {
// Copy over the values to the first object
// Note this will overwrite any values if the key already exists!
jsonData[i][key] = jsonData[j][key];
}
}
// After copying the matching object, delete it from the array
// By deleting this object, the "next" object in the array moves back one
// Therefore it will be what j is prior to being incremented
// This is why we don't automatically increment
jsonData.splice(j, 1);
} else {
// If there's no match, increment to the next object to check
j++;
}
}
}
Note there is no defensive code in this sample; you probably want to add a few checks to make sure the data you have is formatted correctly before passing it along.
Also keep in mind that you might have to decide how to handle instances where two keys overlap but do not match (e.g. two objects both having machine1, but one with the value of 5 and the other with the value of 9). As is, whatever object comes later in the array will take precedence.
const mergeUnique = (list, $M = new Map(), id) => {
list.map(e => $M.has(e[id]) ? $M.set(e[id], { ...e, ...$M.get(e[id]) }) : $M.set(e[id], e));
return Array.from($M.values());
};
id would be x in your case
i created a jsperf with email as identifier: https://jsperf.com/mergeobjectswithmap/
it's a lot faster :)
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]
);
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?
I was trying to create a 3-dimensional array and couldn't find an easy way to do it.
array = [[[]]];
or
array = [][][];
or
array = []; array[] = []; array[][] = [];
would for example not work. (the console'd say the second array is 'undefined' and not an object, or for the second and third example give a parse error).
I cannot hard-code the information either, as I have no idea what the indexes and contents of the array are going to be (they are created 'on the fly' and depending on the input of a user. eg the first array might have the index 4192). I may have to create every array before assigning them, but it would be so much easier and faster if there's an easier way to define 3-dimensional arrays. (there'll be about 2 arrays, 25 subarrays and 800 subsubarrays total) every millisecond saves a life, so to say.
help please?
JavaScript is dynamically typed. Just store arrays in an array.
function loadRow() {
return [1, 2, 3];
}
var array = [];
array.push(loadRow());
array.push(loadRow());
console.log(array[1][2]); // prints 3
Since arrays in javascript aren't true arrays, there isn't really a multidimensional array. In javascript, you just have an arrays within an array. You can define the array statically like this:
var a = [
[1,2,3],
[4,5,6],
[7,8,9]
];
Or dynamically like this:
var d = [];
var d_length = 10;
for (var i = 0;i<d_length;i++) {
d[i] = [];
}
UPDATE
You could also use some helper functions:
function ensureDimensions(arr,i,j,k) {
if(!arr[i]) {
arr[i] = [];
}
if(!arr[i][j]) {
arr[i][j] = [];
}
}
function getValue(arr,i,j,k) {
ensureDimensions(i,j,k);
return arr[i][j][k];
}
function setValue(arr,newVal,i,j,k) {
ensureDimensions(i,j,k);
arr[i][j][k] = newVal;
}