Converting a JS object to an array using jQuery - javascript

My application creates a JavaScript object, like the following:
myObj= {1:[Array-Data], 2:[Array-Data]}
But I need this object as an array.
array[1]:[Array-Data]
array[2]:[Array-Data]
So I tried to convert this object to an array by iterating with $.each through the object and adding the element to an array:
x=[]
$.each(myObj, function(i,n) {
x.push(n);});
Is there an better way to convert an object to an array or maybe a function?

If you are looking for a functional approach:
var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });
Results in:
[11, 22]
The same with an ES6 arrow function:
Object.keys(obj).map(key => obj[key])
With ES7 you will be able to use Object.values instead (more information):
var arr = Object.values(obj);
Or if you are already using Underscore/Lo-Dash:
var arr = _.values(obj)

var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
var array = $.map(myObj, function(value, index) {
return [value];
});
console.log(array);
Output:
[[1, 2, 3], [4, 5, 6]]

Simply do
Object.values(obj);
That's all!

I think you can use for in but checking if the property is not inerithed
myObj= {1:[Array-Data], 2:[Array-Data]}
var arr =[];
for( var i in myObj ) {
if (myObj.hasOwnProperty(i)){
arr.push(myObj[i]);
}
}
EDIT - if you want you could also keep the indexes of your object, but you have to check if they are numeric (and you get undefined values for missing indexes:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
myObj= {1:[1,2], 2:[3,4]}
var arr =[];
for( var i in myObj ) {
if (myObj.hasOwnProperty(i)){
if (isNumber(i)){
arr[i] = myObj[i];
}else{
arr.push(myObj[i]);
}
}
}

If you know the maximum index in you object you can do the following:
var myObj = {
1: ['c', 'd'],
2: ['a', 'b']
},
myArr;
myObj.length = 3; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']]

Since ES5 Object.keys() returns an array containing the properties defined directly on an object (excluding properties defined in the prototype chain):
Object.keys(yourObject).map(function(key){ return yourObject[key] });
ES6 takes it one step further with arrow functions:
Object.keys(yourObject).map(key => yourObject[key]);

Nowadays, there is a simple way to do this : Object.values().
var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
console.log(Object.values(myObj));
Output:
[[1, 2, 3], [4, 5, 6]]
This doesn't required jQuery, it's been defined in ECMAScript 2017.
It's supported by every modern browser (forget IE).

The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);

x = [];
for( var i in myObj ) {
x[i] = myObj[i];
}

ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 or ES6:
Object.keys(myObj).map(x => myObj[x])

How about jQuery.makeArray(obj)
This is how I did it in my app.

ES8 way made easy:
The official documentation
const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr);

The solving is very simple
var my_obj = {1:[Array-Data], 2:[Array-Data]}
Object.keys(my_obj).map(function(property_name){
return my_obj[property_name];
});

Fiddle Demo
Extension to answer of bjornd .
var myObj = {
1: [1, [2], 3],
2: [4, 5, [6]]
}, count = 0,
i;
//count the JavaScript object length supporting IE < 9 also
for (i in myObj) {
if (myObj.hasOwnProperty(i)) {
count++;
}
}
//count = Object.keys(myObj).length;// but not support IE < 9
myObj.length = count + 1; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr);
Reference
Array.prototype.slice()
Function.prototype.apply()
Object.prototype.hasOwnProperty()
Object.keys()

If you want to keep the name of the object's properties as values. Example:
var fields = {
Name: { type: 'string', maxLength: 50 },
Age: { type: 'number', minValue: 0 }
}
Use Object.keys(), Array.map() and Object.assign():
var columns = Object.keys( fields ).map( p => Object.assign( fields[p], {field:p} ) )
Result:
[ { field: 'Name', type: 'string', maxLength: 50 },
{ field: 'Age', type: 'number', minValue: 0 } ]
Explanation:
Object.keys() enumerates all the properties of the source ; .map() applies the => function to each property and returns an Array ; Object.assign() merges name and value for each property.

I made a custom function:
Object.prototype.toArray=function(){
var arr=new Array();
for( var i in this ) {
if (this.hasOwnProperty(i)){
arr.push(this[i]);
}
}
return arr;
};

After some tests, here is a general object to array function convertor:
You have the object:
var obj = {
some_key_1: "some_value_1"
some_key_2: "some_value_2"
};
The function:
function ObjectToArray(o)
{
var k = Object.getOwnPropertyNames(o);
var v = Object.values(o);
var c = function(l)
{
this.k = [];
this.v = [];
this.length = l;
};
var r = new c(k.length);
for (var i = 0; i < k.length; i++)
{
r.k[i] = k[i];
r.v[i] = v[i];
}
return r;
}
Function Use:
var arr = ObjectToArray(obj);
You Get:
arr {
key: [
"some_key_1",
"some_key_2"
],
value: [
"some_value_1",
"some_value_2"
],
length: 2
}
So then you can reach all keys & values like:
for (var i = 0; i < arr.length; i++)
{
console.log(arr.key[i] + " = " + arr.value[i]);
}
Result in console:
some_key_1 = some_value_1
some_key_2 = some_value_2
Edit:
Or in prototype form:
Object.prototype.objectToArray = function()
{
if (
typeof this != 'object' ||
typeof this.length != "undefined"
) {
return false;
}
var k = Object.getOwnPropertyNames(this);
var v = Object.values(this);
var c = function(l)
{
this.k = [];
this.v = [];
this.length = l;
};
var r = new c(k.length);
for (var i = 0; i < k.length; i++)
{
r.k[i] = k[i];
r.v[i] = v[i];
}
return r;
};
And then use like:
console.log(obj.objectToArray);

You can create a simple function to do the conversion from object to array, something like this can do the job for you using pure javascript:
var objectToArray = function(obj) {
var arr = [];
if ('object' !== typeof obj || 'undefined' === typeof obj || Array.isArray(obj)) {
return obj;
} else {
Object.keys(obj).map(x=>arr.push(obj[x]));
}
return arr;
};
or this one:
var objectToArray = function(obj) {
var arr =[];
for(let o in obj) {
if (obj.hasOwnProperty(o)) {
arr.push(obj[o]);
}
}
return arr;
};
and call and use the function as below:
var obj = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'};
objectToArray(obj); // return ["a", "b", "c", "d", "e"]
Also in the future we will have something called Object.values(obj), similar to Object.keys(obj) which will return all properties for you as an array, but not supported in many browsers yet...

Related

how to split a js object into an array of key-value pairs?

Let's say I have an object like this:
var myObject = {
X:1,
Y:2,
Z:3
}
Let's say I want to create a for loop to process each property on the object. The code below is just intended to be some pseudocode to communicate what I'm looking to do:
var properties = myObject.split();
for(var i = 0; i < properties.length; i++)
{
var x = properties[i][key];
var y = properties[i][value]
}
Can you recommend some code I can use to accomplish this in Javascript/TypeScript?
You could use the Object.entries function to get all the key and value pairs as an array of arrays:
Object.entries(myObject);
Which would return:
[['X', 1], ['Y', 2], ['Z' 3]]
And you could iterate through them:
for(const [key, value] of Object.entries(myObject)) {
console.log(key, value);
}
Which would log out:
X 1
Y 2
Z 3
Do note that this is a relatively new feature with no support on IE nor Opera. You can use the polyfill from MDN or use any of the other methods (for…in with hasOwnProperty, Object.keys, etc.).
var arr = {
X:1,
Y:2,
Z:3
};
Object.keys(arr).map(key => { console.log(key, arr[key]) })
Here is the solution.
var arr = {
X:1,
Y:2,
Z:3
};
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
console.log(key + " -> " + arr[key]);
}
}
Another way you can do is
var arr = {
X:1,
Y:2,
Z:3
};
Object.keys(arr).forEach(key => { console.log(key, arr[key]) })
Best practice is typically using Object.keys().
var keys = Object.keys(myObject);
for(var i = 0; i < keys; i++) {
var key, value;
key = Object.keys[i];
value = myObject[key];
// .. do something else ..
}
You can do this Object keys method. Create a custom function and add it to the prototype of the Object like,
var myObject = {
X: 1,
Y: 2,
Z: 3
}
Object.prototype.mySplit = function() {
return Object.keys(this).map((key) => {
return {
key: key,
value: this[key]
};
});
}
var properties = myObject.mySplit();
for (var i = 0; i < properties.length; i++) {
console.log(properties[i]['key'], properties[i]['value']);
}

Array of objects with key/value pairs from given arrays of keys & values

I am trying to return an array of key-value pairs: [{"a": 1},{"b": 2},{"c": 3}] from a given array of keys: ["a", "b", "c"] and an array of values: [1, 2, 3]
I have tried this:
let arr = [], obj = {}, key, val;
const keyValuePairs = (k, v) => {
if (k.length === v.length) {
for (var i = 0; i < k.length; i++) {
key = k[i]; val = v[i];
arr[i] = {key: val};
}
} return arr;
};
keyValuePairs(["a", "b", "c"], [1, 2, 3]);
But it's returning - [ { key: 1 }, { key: 2 }, { key: 3 } ]
How can I do it?
If you're targeting a new enough browser, or are using babel, there is a new syntax that allows this easily:
arr[i] = {[key]: val};
Otherwise you will need to use multiple lines to set the key
let arr = [], obj = {}, key, val;
const keyValuePairs = (k, v) => {
if (k.length === v.length) {
for (var i = 0; i < k.length; i++) {
key = k[i]; val = v[i];
var newObj = {};
newObj[key] = val;
arr[i] = newObj;
}
} return arr;
};
Just general code comments: You have a bunch of variables out of the scope of the function. It's also quite verbose. You can write the entire function like this:
const keyValuePairs = (k, v) => (
k.map((key, index) => ({ [key]: v[index] }))
);
a = ["a", "b", "c"], b = [1, 2, 3]
c = a.map((k, i) => ({[k]: b[i]}))
console.log(JSON.stringify(c))
How do I zip two arrays in JavaScript?
Try this(simple solution):
var answer = keyValuePairs(["a", "b", "c"], [1, 2, 3]);
console.log(answer);
function keyValuePairs(arrOne, arrTwo){
var returnArr = [];
for(var i = 0; i < arrOne.length; i++){
var obj = {};
obj[arrOne[i]] = arrTwo[i];
returnArr[i] = obj;
}
return returnArr;
}
using lodash you can do this in one line with _.map or the vanilla Array.prototype.map and using the index i to stripe across the arrays.
var keys = 'abc'.split('');
var values = '123'.split('');
var result = _.map(keys, (key, i) => ( { [keys[i]] : values[i] } ) );
console.log(JSON.stringify(result));
yields:
[{"a":"1"},{"b":"2"},{"c":"3"}]
you can also continue this pattern dimensionally:
var keys = 'abc'.split('');
var values = '123'.split('');
var valuesValues = 'xyz'.split('');
var result = _.map(keys, (key, i) => ( { [keys[i]] : { [ values[i] ]: valuesValues[i] } } ) );
console.log(JSON.stringify(result));
yields:
[{"a":{"1":"x"}},{"b":{"2":"y"}},{"c":{"3":"z"}}]
you can use reduce method also as per your requirement.
see below example..
let keys = ["a", "b", "c"],
values = [1, 2, 3],
result = keys.reduce((r,v,i)=>r.concat({[v]:values[i]}),[]);
console.log(result);;

how to make array of object using an array?

I have one array
var ar=['aa','cc','po']
I want to push objects in new array after checking the value of given array .In other words
I have these given conditions
var ar=['aa','cc','po']
var arr =[{name:"po"},{name:'aa'},{name:'cc'}];
Expected Output in new Array
[{name:'aa'},{name:'cc'},{name:"po"}]
As "aa" in in 0 index then I added object whose name property aa.
I try like this .but I used two for look .is there any simple way to do this
FIDDLE
var newArr=[];
for(var i=0;i<ar.length ;i++){
var text =ar[i];
for(var j=0;j<arr.length ;j++){
var obj =arr[j];
console.log(obj.name);
/*if(obj.name===text){
newArr.push(obj);
}*/
}
}
console.log(newArr);
This is a proposal in two part, first build an object with the reference to the items of arr and the create a new array with the given items of ar.
var ar = ['aa', 'cc', 'po'],
arr = [{ name: "po" }, { name: 'aa' }, { name: 'cc' }],
object = Object.create(null),
result = [];
arr.forEach(function (a) {
object[a.name] = a;
});
ar.forEach(function (a) {
object[a] && result.push(object[a]);
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Using forEach iterator and generate object reference based on name and then generate result array using map()
var ar = ['aa', 'cc', 'po']
var arr = [{
name: "po"
}, {
name: 'aa'
}, {
name: 'cc'
}];
var ref = {};
// generating object reference with name property
arr.forEach(function(v) {
ref[v.name] = v;
});
// generating result array
// or you can use forEach as #NinaScholz answer
var res = ar.map(function(v) {
return ref[v];
}).filter(function(v) { // use filter to avoid null values , in case of missing elements
return v != null;
});
document.write('<pre>' + JSON.stringify(res, null, 3) + '</pre>');
Try this:
function convert(source) {
var
obj = [],
i;
for (i = 0; i < source.length; ++i) {
obj.push({name: source[i]});
}
return obj;
}
convert(['aa', 'bb', 'cc']); // [{name:'aa'},{name:'bb'},{name:'cc'}]
This would work if you want to assign values from array in sequence:
var ar=['aa','cc','po']
var arr =[{name:"po"},{name:'aa'},{name:'cc'}];
arr.map(function(obj,key){
obj.name = ar[key];
});
console.log(arr);
Do like this
var ar = ['aa', 'cc', 'po']
var arr = [{ name: "po"}, { name: 'aa'}, { name: 'cc'}];
$.each(ar, function(i, v) {
arr[i].name = v;
});
console.log(arr)
Fiddle
var array=['a','b','c'];
var arrayObj=[];
for(var i=0;i<array.length;i++){
var obj={};
obj.name=array[i];
arrayObj.push(obj);
}
console.log(JSON.stringify(arrayObj));
Output:
[{"name":"a"},{"name":"b"},{"name":"c"}]
I guess this is one very functional way of doing this job with no more than an assignment line. However Anoop Joshi's answer is more elegant provided that the ar array is shorter than equal to in length to the arr array.
var arr = ['aa','cc','po'],
ar = [{name:"po"},{name:'aa'},{name:'cc'}],
res = arr.map(e => ar[ar.findIndex(f => f.name == e)]);
document.write("<pre>" + JSON.stringify(res) + "</pre>");

From js object to array [duplicate]

My application creates a JavaScript object, like the following:
myObj= {1:[Array-Data], 2:[Array-Data]}
But I need this object as an array.
array[1]:[Array-Data]
array[2]:[Array-Data]
So I tried to convert this object to an array by iterating with $.each through the object and adding the element to an array:
x=[]
$.each(myObj, function(i,n) {
x.push(n);});
Is there an better way to convert an object to an array or maybe a function?
If you are looking for a functional approach:
var obj = {1: 11, 2: 22};
var arr = Object.keys(obj).map(function (key) { return obj[key]; });
Results in:
[11, 22]
The same with an ES6 arrow function:
Object.keys(obj).map(key => obj[key])
With ES7 you will be able to use Object.values instead (more information):
var arr = Object.values(obj);
Or if you are already using Underscore/Lo-Dash:
var arr = _.values(obj)
var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
var array = $.map(myObj, function(value, index) {
return [value];
});
console.log(array);
Output:
[[1, 2, 3], [4, 5, 6]]
Simply do
Object.values(obj);
That's all!
I think you can use for in but checking if the property is not inerithed
myObj= {1:[Array-Data], 2:[Array-Data]}
var arr =[];
for( var i in myObj ) {
if (myObj.hasOwnProperty(i)){
arr.push(myObj[i]);
}
}
EDIT - if you want you could also keep the indexes of your object, but you have to check if they are numeric (and you get undefined values for missing indexes:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
myObj= {1:[1,2], 2:[3,4]}
var arr =[];
for( var i in myObj ) {
if (myObj.hasOwnProperty(i)){
if (isNumber(i)){
arr[i] = myObj[i];
}else{
arr.push(myObj[i]);
}
}
}
If you know the maximum index in you object you can do the following:
var myObj = {
1: ['c', 'd'],
2: ['a', 'b']
},
myArr;
myObj.length = 3; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr); //[undefined, ['c', 'd'], ['a', 'b']]
Since ES5 Object.keys() returns an array containing the properties defined directly on an object (excluding properties defined in the prototype chain):
Object.keys(yourObject).map(function(key){ return yourObject[key] });
ES6 takes it one step further with arrow functions:
Object.keys(yourObject).map(key => yourObject[key]);
Nowadays, there is a simple way to do this : Object.values().
var myObj = {
1: [1, 2, 3],
2: [4, 5, 6]
};
console.log(Object.values(myObj));
Output:
[[1, 2, 3], [4, 5, 6]]
This doesn't required jQuery, it's been defined in ECMAScript 2017.
It's supported by every modern browser (forget IE).
The best method would be using a javascript -only function:
var myArr = Array.prototype.slice.call(myObj, 0);
x = [];
for( var i in myObj ) {
x[i] = myObj[i];
}
ECMASCRIPT 5:
Object.keys(myObj).map(function(x) { return myObj[x]; })
ECMASCRIPT 2015 or ES6:
Object.keys(myObj).map(x => myObj[x])
How about jQuery.makeArray(obj)
This is how I did it in my app.
ES8 way made easy:
The official documentation
const obj = { x: 'xxx', y: 1 };
let arr = Object.values(obj); // ['xxx', 1]
console.log(arr);
The solving is very simple
var my_obj = {1:[Array-Data], 2:[Array-Data]}
Object.keys(my_obj).map(function(property_name){
return my_obj[property_name];
});
Fiddle Demo
Extension to answer of bjornd .
var myObj = {
1: [1, [2], 3],
2: [4, 5, [6]]
}, count = 0,
i;
//count the JavaScript object length supporting IE < 9 also
for (i in myObj) {
if (myObj.hasOwnProperty(i)) {
count++;
}
}
//count = Object.keys(myObj).length;// but not support IE < 9
myObj.length = count + 1; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr);
Reference
Array.prototype.slice()
Function.prototype.apply()
Object.prototype.hasOwnProperty()
Object.keys()
If you want to keep the name of the object's properties as values. Example:
var fields = {
Name: { type: 'string', maxLength: 50 },
Age: { type: 'number', minValue: 0 }
}
Use Object.keys(), Array.map() and Object.assign():
var columns = Object.keys( fields ).map( p => Object.assign( fields[p], {field:p} ) )
Result:
[ { field: 'Name', type: 'string', maxLength: 50 },
{ field: 'Age', type: 'number', minValue: 0 } ]
Explanation:
Object.keys() enumerates all the properties of the source ; .map() applies the => function to each property and returns an Array ; Object.assign() merges name and value for each property.
I made a custom function:
Object.prototype.toArray=function(){
var arr=new Array();
for( var i in this ) {
if (this.hasOwnProperty(i)){
arr.push(this[i]);
}
}
return arr;
};
After some tests, here is a general object to array function convertor:
You have the object:
var obj = {
some_key_1: "some_value_1"
some_key_2: "some_value_2"
};
The function:
function ObjectToArray(o)
{
var k = Object.getOwnPropertyNames(o);
var v = Object.values(o);
var c = function(l)
{
this.k = [];
this.v = [];
this.length = l;
};
var r = new c(k.length);
for (var i = 0; i < k.length; i++)
{
r.k[i] = k[i];
r.v[i] = v[i];
}
return r;
}
Function Use:
var arr = ObjectToArray(obj);
You Get:
arr {
key: [
"some_key_1",
"some_key_2"
],
value: [
"some_value_1",
"some_value_2"
],
length: 2
}
So then you can reach all keys & values like:
for (var i = 0; i < arr.length; i++)
{
console.log(arr.key[i] + " = " + arr.value[i]);
}
Result in console:
some_key_1 = some_value_1
some_key_2 = some_value_2
Edit:
Or in prototype form:
Object.prototype.objectToArray = function()
{
if (
typeof this != 'object' ||
typeof this.length != "undefined"
) {
return false;
}
var k = Object.getOwnPropertyNames(this);
var v = Object.values(this);
var c = function(l)
{
this.k = [];
this.v = [];
this.length = l;
};
var r = new c(k.length);
for (var i = 0; i < k.length; i++)
{
r.k[i] = k[i];
r.v[i] = v[i];
}
return r;
};
And then use like:
console.log(obj.objectToArray);
You can create a simple function to do the conversion from object to array, something like this can do the job for you using pure javascript:
var objectToArray = function(obj) {
var arr = [];
if ('object' !== typeof obj || 'undefined' === typeof obj || Array.isArray(obj)) {
return obj;
} else {
Object.keys(obj).map(x=>arr.push(obj[x]));
}
return arr;
};
or this one:
var objectToArray = function(obj) {
var arr =[];
for(let o in obj) {
if (obj.hasOwnProperty(o)) {
arr.push(obj[o]);
}
}
return arr;
};
and call and use the function as below:
var obj = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'};
objectToArray(obj); // return ["a", "b", "c", "d", "e"]
Also in the future we will have something called Object.values(obj), similar to Object.keys(obj) which will return all properties for you as an array, but not supported in many browsers yet...

Using jQuery to compare two arrays of Javascript objects

I have two arrays of JavaScript Objects that I'd like to compare to see if they are the same. The objects may not (and most likely will not) be in the same order in each array. Each array shouldn't have any more than 10 objects. I thought jQuery might have an elegant solution to this problem, but I wasn't able to find much online.
I know that a brute nested $.each(array, function(){}) solution could work, but is there any built in function that I'm not aware of?
Thanks.
There is an easy way...
$(arr1).not(arr2).length === 0 && $(arr2).not(arr1).length === 0
If the above returns true, both the arrays are same even if the elements are in different order.
NOTE: This works only for jquery versions < 3.0.0 when using JSON objects
I was also looking for this today and found:
http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256BFB0077DFFD
Don't know if that's a good solution though they do mention some performance considerations taken into account.
I like the idea of a jQuery helper method.
#David I'd rather see your compare method to work like:
jQuery.compare(a, b)
I doesn't make sense to me to be doing:
$(a).compare(b)
where a and b are arrays. Normally when you $(something) you'd be passing a selector string to work with DOM elements.
Also regarding sorting and 'caching' the sorted arrays:
I don't think sorting once at the start of the method instead of every time through the loop is 'caching'. The sort will still happen every time you call compare(b). That's just semantics, but...
for (var i = 0; t[i]; i++) { ...this loop finishes early if your t array contains a false value in it somewhere, so $([1, 2, 3, 4]).compare([1, false, 2, 3]) returns true!
More importantly the array sort() method sorts the array in place, so doing var b = t.sort() ...doesn't create a sorted copy of the original array, it sorts the original array and also assigns a reference to it in b. I don't think the compare method should have side-effects.
It seems what we need to do is to copy the arrays before working on them. The best answer I could find for how to do that in a jQuery way was by none other than John Resig here on SO! What is the most efficient way to deep clone an object in JavaScript? (see comments on his answer for the array version of the object cloning recipe)
In which case I think the code for it would be:
jQuery.extend({
compare: function (arrayA, arrayB) {
if (arrayA.length != arrayB.length) { return false; }
// sort modifies original array
// (which are passed by reference to our method!)
// so clone the arrays before sorting
var a = jQuery.extend(true, [], arrayA);
var b = jQuery.extend(true, [], arrayB);
a.sort();
b.sort();
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
});
var a = [1, 2, 3];
var b = [2, 3, 4];
var c = [3, 4, 2];
jQuery.compare(a, b);
// false
jQuery.compare(b, c);
// true
// c is still unsorted [3, 4, 2]
My approach was quite different - I flattened out both collections using JSON.stringify and used a normal string compare to check for equality.
I.e.
var arr1 = [
{Col: 'a', Val: 1},
{Col: 'b', Val: 2},
{Col: 'c', Val: 3}
];
var arr2 = [
{Col: 'x', Val: 24},
{Col: 'y', Val: 25},
{Col: 'z', Val: 26}
];
if(JSON.stringify(arr1) == JSON.stringify(arr2)){
alert('Collections are equal');
}else{
alert('Collections are not equal');
}
NB: Please note that his method assumes that both Collections are sorted in a similar fashion, if not, it would give you a false result!
Convert both array to string and compare
if (JSON.stringify(array1) == JSON.stringify(array2))
{
// your code here
}
I found this discussion because I needed a way to deep compare arrays and objects. Using the examples here, I came up with the following (broken up into 3 methods for clarity):
jQuery.extend({
compare : function (a,b) {
var obj_str = '[object Object]',
arr_str = '[object Array]',
a_type = Object.prototype.toString.apply(a),
b_type = Object.prototype.toString.apply(b);
if ( a_type !== b_type) { return false; }
else if (a_type === obj_str) {
return $.compareObject(a,b);
}
else if (a_type === arr_str) {
return $.compareArray(a,b);
}
return (a === b);
}
});
jQuery.extend({
compareArray: function (arrayA, arrayB) {
var a,b,i,a_type,b_type;
// References to each other?
if (arrayA === arrayB) { return true;}
if (arrayA.length != arrayB.length) { return false; }
// sort modifies original array
// (which are passed by reference to our method!)
// so clone the arrays before sorting
a = jQuery.extend(true, [], arrayA);
b = jQuery.extend(true, [], arrayB);
a.sort();
b.sort();
for (i = 0, l = a.length; i < l; i+=1) {
a_type = Object.prototype.toString.apply(a[i]);
b_type = Object.prototype.toString.apply(b[i]);
if (a_type !== b_type) {
return false;
}
if ($.compare(a[i],b[i]) === false) {
return false;
}
}
return true;
}
});
jQuery.extend({
compareObject : function(objA,objB) {
var i,a_type,b_type;
// Compare if they are references to each other
if (objA === objB) { return true;}
if (Object.keys(objA).length !== Object.keys(objB).length) { return false;}
for (i in objA) {
if (objA.hasOwnProperty(i)) {
if (typeof objB[i] === 'undefined') {
return false;
}
else {
a_type = Object.prototype.toString.apply(objA[i]);
b_type = Object.prototype.toString.apply(objB[i]);
if (a_type !== b_type) {
return false;
}
}
}
if ($.compare(objA[i],objB[i]) === false){
return false;
}
}
return true;
}
});
Testing
var a={a : {a : 1, b: 2}},
b={a : {a : 1, b: 2}},
c={a : {a : 1, b: 3}},
d=[1,2,3],
e=[2,1,3];
console.debug('a and b = ' + $.compare(a,b)); // a and b = true
console.debug('b and b = ' + $.compare(b,b)); // b and b = true
console.debug('b and c = ' + $.compare(b,c)); // b and c = false
console.debug('c and d = ' + $.compare(c,d)); // c and d = false
console.debug('d and e = ' + $.compare(d,e)); // d and e = true
In my case compared arrays contain only numbers and strings. This solution worked for me:
function are_arrs_equal(arr1, arr2){
return arr1.sort().toString() === arr2.sort().toString()
}
Let's test it!
arr1 = [1, 2, 3, 'nik']
arr2 = ['nik', 3, 1, 2]
arr3 = [1, 2, 5]
console.log (are_arrs_equal(arr1, arr2)) //true
console.log (are_arrs_equal(arr1, arr3)) //false
I don't think there's a good "jQuery " way to do this, but if you need efficiency, map one of the arrays by a certain key (one of the unique object fields), and then do comparison by looping through the other array and comparing against the map, or associative array, you just built.
If efficiency is not an issue, just compare every object in A to every object in B. As long as |A| and |B| are small, you should be okay.
Well, if you want to compare only the contents of arrays, there's a useful jQuery function $.inArray()
var arr = [11, "String #1", 14, "String #2"];
var arr_true = ["String #1", 14, "String #2", 11]; // contents are the same as arr
var arr_false = ["String #1", 14, "String #2", 16]; // contents differ
function test(arr_1, arr_2) {
var equal = arr_1.length == arr_2.length; // if array sizes mismatches, then we assume, that they are not equal
if (equal) {
$.each(arr_1, function (foo, val) {
if (!equal) return false;
if ($.inArray(val, arr_2) == -1) {
equal = false;
} else {
equal = true;
}
});
}
return equal;
}
alert('Array contents are the same? ' + test(arr, arr_true)); //- returns true
alert('Array contents are the same? ' + test(arr, arr_false)); //- returns false
Change array to string and compare
var arr = [1,2,3],
arr2 = [1,2,3];
console.log(arr.toString() === arr2.toString());
The nice one liner from Sudhakar R as jQuery global method.
/**
* Compare two arrays if they are equal even if they have different order.
*
* #link https://stackoverflow.com/a/7726509
*/
jQuery.extend({
/**
* #param {array} a
* First array to compare.
* #param {array} b
* Second array to compare.
* #return {boolean}
* True if both arrays are equal, otherwise false.
*/
arrayCompare: function (a, b) {
return $(a).not(b).get().length === 0 && $(b).not(a).get().length === 0;
}
});
I also found this when looking to do some array comparisons with jQuery. In my case I had strings which I knew to be arrays:
var needle = 'apple orange';
var haystack = 'kiwi orange banana apple plum';
But I cared if it was a complete match or only a partial match, so I used something like the following, based off of Sudhakar R's answer:
function compareStrings( needle, haystack ){
var needleArr = needle.split(" "),
haystackArr = haystack.split(" "),
compare = $(haystackArr).not(needleArr).get().length;
if( compare == 0 ){
return 'all';
} else if ( compare == haystackArr.length ) {
return 'none';
} else {
return 'partial';
}
}
If duplicates matter such that [1, 1, 2] should not be equal to [2, 1] but should equal [1, 2, 1], here is a reference counting solution:
const arrayContentsEqual = (arrayA, arrayB) => {
if (arrayA.length !== arrayB.length) {
return false}
const refCount = (function() {
const refCountMap = {};
const refCountFn = (elt, count) => {
refCountMap[elt] = (refCountMap[elt] || 0) + count}
refCountFn.isZero = () => {
for (let elt in refCountMap) {
if (refCountMap[elt] !== 0) {
return false}}
return true}
return refCountFn})()
arrayB.map(eltB => refCount(eltB, 1));
arrayA.map(eltA => refCount(eltA, -1));
return refCount.isZero()}
Here is the fiddle to play with.
var arr1 = [
{name: 'a', Val: 1},
{name: 'b', Val: 2},
{name: 'c', Val: 3}
];
var arr2 = [
{name: 'c', Val: 3},
{name: 'x', Val: 4},
{name: 'y', Val: 5},
{name: 'z', Val: 6}
];
var _isEqual = _.intersectionWith(arr1, arr2, _.isEqual);// common in both array
var _difference1 = _.differenceWith(arr1, arr2, _.isEqual);//difference from array1
var _difference2 = _.differenceWith(arr2, arr1, _.isEqual);//difference from array2
console.log(_isEqual);// common in both array
console.log(_difference1);//difference from array1
console.log(_difference2);//difference from array2
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>
Try this
function check(c,d){
var a = c, b = d,flg = 0;
if(a.length == b.length)
{
for(var i=0;i<a.length;i++)
a[i] != b[i] ? flg++ : 0;
}
else
{
flg = 1;
}
return flg = 0;
}

Categories