How to check if array contains at least one object ? - javascript

I want to check if array contains object or not. I am not trying to compare values just want to check in my array if object is present or not?
Ex.
$arr = ['a','b','c'] // normal
$arr = [{ id: 1}, {id: 2}] // array of objects
$arr = [{id: 1}, {id:2}, 'a', 'b'] // mix values
So how can i check if array contains object

You can use some method which tests whether at least one element in the array passes the test implemented by the provided function.
let arr = [{id: 1}, {id:2}, 'a', 'b'];
let exists = arr.some(a => typeof a == 'object');
console.log(exists);

I want to check if array contains object or not
Use some to simply check if any item of the array has value of type "object"
var hasObject = $arr.some( function(val){
return typeof val == "object";
});

var hasObject = function(arr) {
for (var i=0; i<arr.length; i++) {
if (typeof arr[i] == 'object') {
return true;
}
}
return false;
};
console.log(hasObject(['a','b','c']));
console.log(hasObject([{ id: 1}, {id: 2}]));
console.log(hasObject([{id: 1}, {id:2}, 'a', 'b']));

You could count the objects and use it for one of the three types to return.
function getType(array) {
var count = array.reduce(function (r, a) {
return r + (typeof a === 'object');
}, 0);
return count === array.length
? 'array of objects'
: count
? 'mix values'
: 'normal';
}
console.log([
['a', 'b', 'c'],
[{ id: 1 }, { id: 2 }],
[{ id: 1 }, { id: 2 }, 'a', 'b']
].map(getType));

With a type check on array
const hasObject = a => Array.isArray(a) && a.some(val => typeof val === 'object')

Related

Transform JS collection to an object with specific keys and grouped values

I would like to create this JS function with these arguments:
transform([{a:1, b:'1', c:true},{a:'1', b:2, c:3, d:false}, {a:1, c:'test'}], ['a','b','c']);
First argument is an array of objects
Second one is array of keys.
I would like to get this output object:
{a:[1, '1', 1], b:['1', 2],c:[true, 3, 'test']}
As you can see the second argument became the keys to the created object
and all values under these keys where grouped together.
And maybe an option to pass a unique argument to function and get this (duplicate values removed):
{a:[1, '1'], b:['1', 2], c:[true, 3, 'test']}
What is the fast and/or elegant way to do it?
Is there any lodash/underscore helper for it?
As an additional generalism. How can the input (the first argument) be a generic collection with nested levels (array or object of nested levels of arrays or objects) ?
Thanks.
You can use Array.prototype.reduce
let param1 = [{a:1,b:'1',c:true},{a:'1',b:2,c:3,d:false},{a:1,c:'test'}];
let param2 = ['a', 'b', 'c'];
function test(objArr, keys) {
let returnObject = {};
keys.forEach(key => returnObject[key] = []);
return objArr.reduce((ret, obj) => {
keys.forEach(key => {
if (obj[key] !== undefined)
ret[key].push(obj[key]);
});
return ret;
}, returnObject);
}
console.log(JSON.stringify(test(param1, param2)));
Outputs:
{"a":[1,"1",1],"b":["1",2],"c":[true,3,"test"]}
Try this:
function transform(data,keys){
let results = {};
//loop all you keys
keys.forEach(index => {
//loop your arrays
data.forEach(element => {
//if there is a match add the key to the results object
if(index in element) {
if(!(index in results)) results[index] = [];
//check if a value already exists for a given key.
if(!(element[index] in results[index])) results[index].push(element[index]);
}
});
});
return results;
}
console.log(transform([{a:1,b:'1',c:true},{a:'1',b:2,c:3,d:false},{a:1,c:'test'}], ['a','b','c']));
You can loop over the key array and pass this key to another function which will use forEach method. This getMatchedKeyValues using forEachwill return an array of elements whose key matches
var arr = [{
a: 1,
b: '1',
c: true
}, {
a: '1',
b: 2,
c: 3,
d: false
}, {
a: 1,
c: 'test'
}];
var keys = ['a', 'b', 'c']
function transform(keyArray) {
var newObj = {};
// looping over key array
keyArray.forEach(function(item) {
// adding key property and calling a function which will return
// an array of elements whose key is same
newObj[item] = getMatchedKeyValues(item)
})
return newObj;
}
function getMatchedKeyValues(keyName) {
var valArray = [];
arr.forEach(function(item) {
if (item[keyName]) {
valArray.push(item[keyName])
}
})
return valArray;
}
console.log(transform(keys))
I coded below , pls have a look this solution.
function test(arr, arr1) {
return arr.reduce((total, current) => {
arr1.forEach(curr => {
if (typeof total[curr] === "undefined") total[curr] = [];
if (current[curr]) total[curr].push(current[curr]);
});
return total;
}, {});
}
console.log(
test(
[
{ a: 1, b: "1", c: true },
{ a: "1", b: 2, c: 3, d: false },
{ a: 1, c: "test" }
],
["a", "b", "c"]
)
);

Add item to array or substitute it if it has the same id

I have this array of objects
var source = [
{id: 1, label: "one"},
{id: 2, label: "two"},
{id: 3, label: "three"}
];
I need to add an item or substitute it if it has the same id
var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 4, label: "four"};
source = myFunc(new_sub);
source = myFunc(new_add);
function myFunc(obj) {
return (source.findIndex(x => x.id === obj.id) === -1) ?
source.concat(obj) : source.map((item) => {
return (item.id === obj.id) ? obj : item;
});
}
This code works perfectly, but is there a better way to do this?
You can check my code to this snippit:
var source = [
{id: 1, label: "one"},
{id: 2, label: "two"},
{id: 3, label: "three"}
];
var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 4, label: "four"};
source = myFunc(new_sub);
source = myFunc(new_add);
function myFunc(obj) {
return (source.findIndex(x => x.id === obj.id) === -1) ?
source.concat(obj) : source.map((item) => {
return (item.id === obj.id) ? obj : item;
});
}
//PRINT
var html = "";
source.map((item) => {
html += "<li>" + item.id + " - " + item.label + "</li>";
});
$("#resp").html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="resp">
</ul>
You're making multiple passes over the array (one in findIndex, then one in either concat or map), which is unnecessary. Just a single pass will do it:
function myFunc(a, obj) {
let found = false;
const result = a.map(e => {
if (!found && e.id === obj.id) {
found = true;
return obj;
} else {
return e;
}
});
if (!found) {
result.push(obj);
}
return result;
}
Note that I passed the source array into the function as an argument, so it doesn't have side-effects.
var source = [
{id: 1, label: "one"},
{id: 2, label: "two"},
{id: 3, label: "three"}
];
var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 4, label: "four"};
source = myFunc(source, new_sub);
source = myFunc(source, new_add);
console.log(source);
function myFunc(a, obj) {
let found = false;
const result = a.map(e => {
if (!found && e.id === obj.id) {
found = true;
return obj;
} else {
return e;
}
});
if (!found) {
result.push(obj);
}
return result;
}
Of course, if the array is small and you know that's the standard case, it doesn't really matter.
If you want to be concise at the expense of (in my view) abusing the , operator:
function myFunc(a, obj) {
let found = false;
const result = a.map(e => e.id === obj.id ? (found = true, obj) : e);
if (!found) {
result.push(obj);
}
return result;
}
function myFunc(obj) {
let i = source.findIndex(x => x.id === obj.id); // get the index
if(i === -1) sources.push(obj); // if there isn't any object that have the same id, then push this obj into the array
else sources[i] = obj; // if there is then replace it
return sources; // this won't be necessary the array get mutated so no need to store it back into sources (see note bellow)
}
Note: Your version of myFunc creates a new array each time it is called. My version doesn't. But since you are storing the return value of myFunc back into sources, I guess creating a new array isn't needed (in my version you won't have to do sources = myFunc(...) as the array sources get mutated).
Older browsers support: (and actually better)
function myFunc(obj) {
for (var i = 0; i < sources.length && sources[i].id !== obj.id; i++) // stop when reaching the end of the array or when we find an object with the same id
; // empty loop (just using it to find the index)
sources[i] = obj; // i will be either the index of the found object (so it will be replaced by obj) or sources.length (so obj will be added to the array)
}
If you do this often (insert a few thousand elements) it may be better (concerning performance) to build up a hash table ( which has a lookup time of O(1) instead of O(n) for searching an array):
var source = [
{id: 1, label: "one"},
{id: 2, label: "two"},
{id: 3, label: "three"}
];
var hash = new Map(source.map((el,i)=>[el.id,i]));
function substitute(elem){
var i = hash.get(elem.id);
if(i !== undefined){
return source[i] = elem;
}
hash.set(elem.id,source.push(elem));
}
In action
function myFunc( o )
{
let i ;
if ( (i = source[0].indexOf(o.id)) < 0 )
{
source[0].push(o.id) ; source.push(o)
}
else
{
source[1 + i] = o
}
// return JSON.parse(JSON.stringify(source)) // new Array with primitives
return source // As reference
}
var source = [
[4, 1, 3, 2] // the trick here
, {id: 4, label: "four"}
, {id: 1, label: "one"}
, {id: 3, label: "three"}
, {id: 2, label: "two"}
];
var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 6, label: "six new label"};
source = myFunc(new_sub);
console.log("// => source after new sub", source);
source = myFunc(new_add);
console.log("// => source after new add", source);

TypeScript - Take object out of array based on attribute value

My array looks like this:
array = [object {id: 1, value: "itemname"}, object {id: 2, value: "itemname"}, ...]
all my objects have the same attibutes, but with different values.
Is there an easy way I can use a WHERE statement for that array?
Take the object where object.id = var
or do I just need to loop over the entire array and check every item? My array has over a 100 entries, so I wanted to know if there was a more efficient way
Use Array.find:
let array = [
{ id: 1, value: "itemname" },
{ id: 2, value: "itemname" }
];
let item1 = array.find(i => i.id === 1);
Array.find at MDN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find
I'd use filter or reduce:
let array = [
{ id: 1, value: "itemname" },
{ id: 2, value: "itemname" }
];
let item1 = array.filter(item => item.id === 1)[0];
let item2 = array.reduce((prev, current) => prev || current.id === 1 ? current : null);
console.log(item1); // Object {id: 1, value: "itemname"}
console.log(item2); // Object {id: 1, value: "itemname"}
(code in playground)
If you care about iterating over the entire array then use some:
let item;
array.some(i => {
if (i.id === 1) {
item = i;
return true;
}
return false;
});
(code in playground)
You can search a certain value in array of objects using TypeScript dynamically if you need to search the value from all fields of the object without specifying column
var searchText = 'first';
let items = [
{ id: 1, name: "first", grade: "A" },
{ id: 2, name: "second", grade: "B" }
];
This below code will search for the value
var result = items.filter(item =>
Object.keys(item).some(k => item[k] != null &&
item[k].toString().toLowerCase()
.includes(searchText.toLowerCase()))
);
Same approach can be used to make a Search Filter Pipe in angularjs 4 using TypeScript
I had to declare the type to get it to work in typescript:
let someId = 1
array.find((i: { id: string; }) => i.id === someId)
You'll have to loop over the array, but if you make a hashmap to link each id to an index and save that, you only have to do it once, so you can reference any objeft after that directly:
var idReference = myArray.reduce(function( map, record, index ) {
map[ record.id ] = index;
return map;
}, {});
var objectWithId5 = myArray[ idReference["5"] ];
This does assume all ids are unique though.

Removing duplicates in a array object

I have an array object as follows:
details :
Array[2]
>0: Object
Name:"a"
Desc:"Desc"
>1: Object
Name:"b"
Desc:"Desc2"
>2: Object
Name:"C"
Desc:"Desc"
I want to remove the last object since the "Desc" has the duplicate entry with the first entry.
I tried this approach in javascript,
removedup = details.reduce(function(a,b) { if (a.indexOf(b) < 0) a.push(b); return a },[]);
I want the output, to remove the duplicates and therefore adjust the array size.
details :
Array[1]
>0: Object
Name:"a"
Desc:"Desc"
>1: Object
Name:"b"
Desc:"Desc2"
what can I modify in logic?
You could use Array#filter() and thisArgs for a temporary object.
var details = [{ Name: 'a', desc: 'Desc' }, { Name: 'b', desc: 'Desc2' }, { Name: 'C', desc: 'Desc' }, {Name: 'a', desc: 'toString'}],
removedup = details.filter(function (a) {
if (!(a.desc in this)) {
this[a.desc] = true;
return true;
}
}, Object.create(null));
document.write('<pre> ' + JSON.stringify(removedup, 0, 4) + '</pre>');
Try this:
var modified = details.filter(function (item) {
return !details.some(function (item_) {
return item_ !== item && item_.Desc === item.Desc;
});
});
Using loadash
var output = _.chain(Array).reverse().indexBy('Desc').toArray().value();

Comparing Arrays of Objects in JavaScript

I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?
As serialization doesn't work generally (only when the order of properties matches: JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})) you have to check the count of properties and compare each property as well:
const objectsEqual = (o1, o2) =>
Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => o1[p] === o2[p]);
const obj1 = { name: 'John', age: 33};
const obj2 = { age: 33, name: 'John' };
const obj3 = { name: 'John', age: 45 };
console.log(objectsEqual(obj1, obj2)); // true
console.log(objectsEqual(obj1, obj3)); // false
If you need a deep comparison, you can call the function recursively:
const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };
const obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };
const obj3 = { name: 'John', age: 33 };
const objectsEqual = (o1, o2) =>
typeof o1 === 'object' && Object.keys(o1).length > 0
? Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
: o1 === o2;
console.log(objectsEqual(obj1, obj2)); // true
console.log(objectsEqual(obj1, obj3)); // false
Then it's easy to use this function to compare objects in arrays:
const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];
const arraysEqual = (a1, a2) =>
a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));
console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3)); // false
EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply serialize the two arrays to JSON and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to each of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend MochiKit.
EDIT: The answer kamens gave deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).
Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
The assumption is that both objects have the same exact list of properties.
Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)
Honestly, with 8 objects max and 8 properties max per object, your best bet is to just traverse each object and make the comparisons directly. It'll be fast and it'll be easy.
If you're going to be using these types of comparisons often, then I agree with Jason about JSON serialization...but otherwise there's no need to slow down your app with a new library or JSON serialization code.
I know this is an old question and the answers provided work fine ... but this is a bit shorter and doesn't require any additional libraries ( i.e. JSON ):
function arraysAreEqual(ary1,ary2){
return (ary1.join('') == ary2.join(''));
}
I have worked a bit on a simple algorithm to compare contents of two objects and return an intelligible list of difference. Thought I would share. It borrows some ideas for jQuery, namely the map function implementation and the object and array type checking.
It returns a list of "diff objects", which are arrays with the diff info. It's very simple.
Here it is:
// compare contents of two objects and return a list of differences
// returns an array where each element is also an array in the form:
// [accessor, diffType, leftValue, rightValue ]
//
// diffType is one of the following:
// value: when primitive values at that index are different
// undefined: when values in that index exist in one object but don't in
// another; one of the values is always undefined
// null: when a value in that index is null or undefined; values are
// expressed as boolean values, indicated wheter they were nulls
// type: when values in that index are of different types; values are
// expressed as types
// length: when arrays in that index are of different length; values are
// the lengths of the arrays
//
function DiffObjects(o1, o2) {
// choose a map() impl.
// you may use $.map from jQuery if you wish
var map = Array.prototype.map?
function(a) { return Array.prototype.map.apply(a, Array.prototype.slice.call(arguments, 1)); } :
function(a, f) {
var ret = new Array(a.length), value;
for ( var i = 0, length = a.length; i < length; i++ )
ret[i] = f(a[i], i);
return ret.concat();
};
// shorthand for push impl.
var push = Array.prototype.push;
// check for null/undefined values
if ((o1 == null) || (o2 == null)) {
if (o1 != o2)
return [["", "null", o1!=null, o2!=null]];
return undefined; // both null
}
// compare types
if ((o1.constructor != o2.constructor) ||
(typeof o1 != typeof o2)) {
return [["", "type", Object.prototype.toString.call(o1), Object.prototype.toString.call(o2) ]]; // different type
}
// compare arrays
if (Object.prototype.toString.call(o1) == "[object Array]") {
if (o1.length != o2.length) {
return [["", "length", o1.length, o2.length]]; // different length
}
var diff =[];
for (var i=0; i<o1.length; i++) {
// per element nested diff
var innerDiff = DiffObjects(o1[i], o2[i]);
if (innerDiff) { // o1[i] != o2[i]
// merge diff array into parent's while including parent object name ([i])
push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + i + "]" + o[0]; return o; }));
}
}
// if any differences were found, return them
if (diff.length)
return diff;
// return nothing if arrays equal
return undefined;
}
// compare object trees
if (Object.prototype.toString.call(o1) == "[object Object]") {
var diff =[];
// check all props in o1
for (var prop in o1) {
// the double check in o1 is because in V8 objects remember keys set to undefined
if ((typeof o2[prop] == "undefined") && (typeof o1[prop] != "undefined")) {
// prop exists in o1 but not in o2
diff.push(["[" + prop + "]", "undefined", o1[prop], undefined]); // prop exists in o1 but not in o2
}
else {
// per element nested diff
var innerDiff = DiffObjects(o1[prop], o2[prop]);
if (innerDiff) { // o1[prop] != o2[prop]
// merge diff array into parent's while including parent object name ([prop])
push.apply(diff, map(innerDiff, function(o, j) { o[0]="[" + prop + "]" + o[0]; return o; }));
}
}
}
for (var prop in o2) {
// the double check in o2 is because in V8 objects remember keys set to undefined
if ((typeof o1[prop] == "undefined") && (typeof o2[prop] != "undefined")) {
// prop exists in o2 but not in o1
diff.push(["[" + prop + "]", "undefined", undefined, o2[prop]]); // prop exists in o2 but not in o1
}
}
// if any differences were found, return them
if (diff.length)
return diff;
// return nothing if objects equal
return undefined;
}
// if same type and not null or objects or arrays
// perform primitive value comparison
if (o1 != o2)
return [["", "value", o1, o2]];
// return nothing if values are equal
return undefined;
}
I tried JSON.stringify() and worked for me.
let array1 = [1,2,{value:'alpha'}] , array2 = [{value:'alpha'},'music',3,4];
JSON.stringify(array1) // "[1,2,{"value":"alpha"}]"
JSON.stringify(array2) // "[{"value":"alpha"},"music",3,4]"
JSON.stringify(array1) === JSON.stringify(array2); // false
There is a optimized code for case when function needs to equals to empty arrays (and returning false in that case)
const objectsEqual = (o1, o2) => {
if (o2 === null && o1 !== null) return false;
return o1 !== null && typeof o1 === 'object' && Object.keys(o1).length > 0 ?
Object.keys(o1).length === Object.keys(o2).length &&
Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
: (o1 !== null && Array.isArray(o1) && Array.isArray(o2) && !o1.length &&
!o2.length) ? true : o1 === o2;
}
Here is my attempt, using Node's assert module + npm package object-hash.
I suppose that you would like to check if two arrays contain the same objects, even if those objects are ordered differently between the two arrays.
var assert = require('assert');
var hash = require('object-hash');
var obj1 = {a: 1, b: 2, c: 333},
obj2 = {b: 2, a: 1, c: 444},
obj3 = {b: "AAA", c: 555},
obj4 = {c: 555, b: "AAA"};
var array1 = [obj1, obj2, obj3, obj4];
var array2 = [obj3, obj2, obj4, obj1]; // [obj3, obj3, obj2, obj1] should work as well
// calling assert.deepEquals(array1, array2) at this point FAILS (throws an AssertionError)
// even if array1 and array2 contain the same objects in different order,
// because array1[0].c !== array2[0].c
// sort objects in arrays by their hashes, so that if the arrays are identical,
// their objects can be compared in the same order, one by one
var array1 = sortArrayOnHash(array1);
var array2 = sortArrayOnHash(array2);
// then, this should output "PASS"
try {
assert.deepEqual(array1, array2);
console.log("PASS");
} catch (e) {
console.log("FAIL");
console.log(e);
}
// You could define as well something like Array.prototype.sortOnHash()...
function sortArrayOnHash(array) {
return array.sort(function(a, b) {
return hash(a) > hash(b);
});
}
My practice implementation with sorting, tested and working.
const obj1 = { name: 'John', age: 33};
const obj2 = { age: 33, name: 'John' };
const obj3 = { name: 'John', age: 45 };
const equalObjs = ( obj1, obj2 ) => {
let keyExist = false;
for ( const [key, value] of Object.entries(obj1) ) {
// Search each key in reference object and attach a callback function to
// compare the two object keys
if( Object.keys(obj2).some( ( e ) => e == key ) ) {
keyExist = true;
}
}
return keyExist;
}
console.info( equalObjs( obj1, obj2 ) );
Compare your arrays
// Sort Arrays
var arr1 = arr1.sort(( a, b ) => {
var fa = Object.keys(a);
var fb = Object.keys(b);
if (fa < fb) {
return -1;
}
if (fa > fb) {
return 1;
}
return 0;
});
var arr2 = arr2.sort(( a, b ) => {
var fa = Object.keys(a);
var fb = Object.keys(b);
if (fa < fb) {
return -1;
}
if (fa > fb) {
return 1;
}
return 0;
});
const equalArrays = ( arr1, arr2 ) => {
// If the arrays are different length we an eliminate immediately
if( arr1.length !== arr2.length ) {
return false;
} else if ( arr1.every(( obj, index ) => equalObjs( obj, arr2[index] ) ) ) {
return true;
} else {
return false;
}
}
console.info( equalArrays( arr1, arr2 ) );
I am sharing my compare function implementation as it might be helpful for others:
/*
null AND null // true
undefined AND undefined // true
null AND undefined // false
[] AND [] // true
[1, 2, 'test'] AND ['test', 2, 1] // true
[1, 2, 'test'] AND ['test', 2, 3] // false
[undefined, 2, 'test'] AND ['test', 2, 1] // false
[undefined, 2, 'test'] AND ['test', 2, undefined] // true
[[1, 2], 'test'] AND ['test', [2, 1]] // true
[1, 'test'] AND ['test', [2, 1]] // false
[[2, 1], 'test'] AND ['test', [2, 1]] // true
[[2, 1], 'test'] AND ['test', [2, 3]] // false
[[[3, 4], 2], 'test'] AND ['test', [2, [3, 4]]] // true
[[[3, 4], 2], 'test'] AND ['test', [2, [5, 4]]] // false
[{x: 1, y: 2}, 'test'] AND ['test', {x: 1, y: 2}] // true
1 AND 1 // true
{test: 1} AND ['test', 2, 1] // false
{test: 1} AND {test: 1} // true
{test: 1} AND {test: 2} // false
{test: [1, 2]} AND {test: [1, 2]} // true
{test: [1, 2]} AND {test: [1]} // false
{test: [1, 2], x: 1} AND {test: [1, 2], x: 2} // false
{test: [1, { z: 5 }], x: 1} AND {x: 1, test: [1, { z: 5}]} // true
{test: [1, { z: 5 }], x: 1} AND {x: 1, test: [1, { z: 6}]} // false
*/
function is_equal(x, y) {
const
arr1 = x,
arr2 = y,
is_objects_equal = function (obj_x, obj_y) {
if (!(
typeof obj_x === 'object' &&
Object.keys(obj_x).length > 0
))
return obj_x === obj_y;
return Object.keys(obj_x).length === Object.keys(obj_y).length &&
Object.keys(obj_x).every(p => is_objects_equal(obj_x[p], obj_y[p]));
}
;
if (!( Array.isArray(arr1) && Array.isArray(arr2) ))
return (
arr1 && typeof arr1 === 'object' &&
arr2 && typeof arr2 === 'object'
)
? is_objects_equal(arr1, arr2)
: arr1 === arr2;
if (arr1.length !== arr2.length)
return false;
for (const idx_1 of arr1.keys())
for (const idx_2 of arr2.keys())
if (
(
Array.isArray(arr1[idx_1]) &&
this.is_equal(arr1[idx_1], arr2[idx_2])
) ||
is_objects_equal(arr1[idx_1], arr2[idx_2])
)
{
arr2.splice(idx_2, 1);
break;
}
return !arr2.length;
}
Please try this one:
function used_to_compare_two_arrays(a, b)
{
// This block will make the array of indexed that array b contains a elements
var c = a.filter(function(value, index, obj) {
return b.indexOf(value) > -1;
});
// This is used for making comparison that both have same length if no condition go wrong
if (c.length !== a.length) {
return 0;
} else{
return 1;
}
}
The objectsAreSame function mentioned in #JasonBunting's answer works fine for me. However, there's a little problem: If x[propertyName] and y[propertyName] are objects (typeof x[propertyName] == 'object'), you'll need to call the function recursively in order to compare them.
not sure about the performance ... will have to test on big objects .. however, this works great for me.. the advantage it has compared to the other solutions is, the objects/array do not have to be in the same order ....
it practically takes the first object in the first array, and scans the second array for every objects .. if it's a match, it will proceed to another
there is absolutely a way for optimization but it's working :)
thx to #ttulka I got inspired by his work ... just worked on it a little bit
const objectsEqual = (o1, o2) => {
let match = false
if(typeof o1 === 'object' && Object.keys(o1).length > 0) {
match = (Object.keys(o1).length === Object.keys(o2).length && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p])))
}else {
match = (o1 === o2)
}
return match
}
const arraysEqual = (a1, a2) => {
let finalMatch = []
let itemFound = []
if(a1.length === a2.length) {
finalMatch = []
a1.forEach( i1 => {
itemFound = []
a2.forEach( i2 => {
itemFound.push(objectsEqual(i1, i2))
})
finalMatch.push(itemFound.some( i => i === true))
})
}
return finalMatch.every(i => i === true)
}
const ar1 = [
{ id: 1, name: "Johnny", data: { body: "Some text"}},
{ id: 2, name: "Jimmy"}
]
const ar2 = [
{name: "Jimmy", id: 2},
{name: "Johnny", data: { body: "Some text"}, id: 1}
]
console.log("Match:",arraysEqual(ar1, ar2))
jsfiddle: https://jsfiddle.net/x1pubs6q/
or just use lodash :))))
const _ = require('lodash')
const isArrayEqual = (x, y) => {
return _.isEmpty(_.xorWith(x, y, _.isEqual));
};
using _.some from lodash: https://lodash.com/docs/4.17.11#some
const array1AndArray2NotEqual =
_.some(array1, (a1, idx) => a1.key1 !== array2[idx].key1
|| a1.key2 !== array2[idx].key2
|| a1.key3 !== array2[idx].key3);
There`s my solution. It will compare arrays which also have objects and arrays. Elements can be stay in any positions.
Example:
const array1 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];
const array2 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];
const arraysCompare = (a1, a2) => {
if (a1.length !== a2.length) return false;
const objectIteration = (object) => {
const result = [];
const objectReduce = (obj) => {
for (let i in obj) {
if (typeof obj[i] !== 'object') {
result.push(`${i}${obj[i]}`);
} else {
objectReduce(obj[i]);
}
}
};
objectReduce(object);
return result;
};
const reduceArray1 = a1.map(item => {
if (typeof item !== 'object') return item;
return objectIteration(item).join('');
});
const reduceArray2 = a2.map(item => {
if (typeof item !== 'object') return item;
return objectIteration(item).join('');
});
const compare = reduceArray1.map(item => reduceArray2.includes(item));
return compare.reduce((acc, item) => acc + Number(item)) === a1.length;
};
console.log(arraysCompare(array1, array2));
This is work for me to compare two array of objects without taking into consideration the order of the items
const collection1 = [
{ id: "1", name: "item 1", subtitle: "This is a subtitle", parentId: "1" },
{ id: "2", name: "item 2", parentId: "1" },
{ id: "3", name: "item 3", parentId: "1" },
]
const collection2 = [
{ id: "3", name: "item 3", parentId: "1" },
{ id: "2", name: "item 2", parentId: "1" },
{ id: "1", name: "item 1", subtitle: "This is a subtitle", parentId: "1" },
]
const contains = (arr, obj) => {
let i = arr.length;
while (i--) {
if (JSON.stringify(arr[i]) === JSON.stringify(obj)) {
return true;
}
}
return false;
}
const isEqual = (obj1, obj2) => {
let n = 0
if (obj1.length !== obj2.length) {
return false;
}
for (let i = 0; i < obj1.length; i++) {
if (contains(obj2, obj1[i])) {
n++
}
}
return n === obj1.length
}
console.log(isEqual(collection1,collection2))
if you take into consideration the order of the items use built in function in lodash isEqual
comparing with json is pretty bad. try this package to compare nested arrays and get the difference.
https://www.npmjs.com/package/deep-object-diff
If you stringify them...
type AB = {
nome: string;
}
const a: AB[] = [{ nome: 'Célio' }];
const b: AB[] = [{ nome: 'Célio' }];
console.log(a === b); // false
console.log(JSON.stringify(a) === JSON.stringify(b)); // true

Categories

Resources