Pushing Unique JQuery Objects to an Array - javascript

I'm completely new to using Jquery, and I'm trying push unique objects to an array, and if the object is already in the array, it removes them. This is for students to book multiple tutorial classes by clicking on available options, and then submitting the full array with all their selected options.
I've updated my code exactly from what I've written. This code works perfectly if I just use single elements in the array. It cannot evaluate duplicate selected slots if I use objects in the array.
var bookingSlots = [];
$('.row').on('click','.slots', function (e) {
e.preventDefault();
$(this).toggleClass('selected');
var slotID = $(this).attr('data-slot-id');
var studentID = $(this).attr('data-student-id');
var slot = {slotID: slotID, studentID: studentID};
var found = jQuery.inArray(slot,bookingSlots);
if(found < 0){
bookingSlots.push(slot);
}else{
bookingSlots.splice(found, 1);
}
});

From your comment:
the object is being created on every single click
That's the problem: Equivalent objects are not either == or === to each other, and inArray uses === to find the object. For instance, $.inArray({id:1}, [{id:1}]) returns -1:
console.log($.inArray({id:1}, [{id:1}])); // -1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
So you'll want to use something else. On modern browsers, you can use Array#findIndex and use a predicate function:
var index = array.findIndex(function(e) { return e.id == id && e.id2 == id2; });
Example:
var array = [];
run(1, 1); // adds
run(1, 2); // adds
run(1, 1); // removes
console.log(array); // ends up with just the 1,2 object in it
function run(id, id2) {
// Find the equivalent object if any
var index = array.findIndex(function(e) { return e.id == id && e.id2 == id2; });
// Found?
if (index == -1) {
// No, add one
array.push({id: id, id2: id2});
} else {
// Yes, remove it
array.splice(index, 1);
}
}
Array#findIndex can be shimmed/polyfilled on older browsers; MDN has a polyfill here (I've also quoted it below, just in case, but I can't imagine MDN disappearing any time soon).
Side note: It's a bit more concise with ES2015 (aka "ES6") (browsers aren't quite ready for us to use ES2015 in the wild yet, but you can transpile):
let index = array.findIndex(e => e.id == id && e.id2 == id2);
Here's MDN's polyfill as of this writing (25/05/2016):
if (!Array.prototype.findIndex) {
Array.prototype.findIndex = function(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.findIndex called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
};
}

In your situation, I suggest that you should take a look on LINQ JS
Example:
var exObjArr = Enumerable.From(array)
.Where(function(x){return x.id1 == object.id1 && x.id2 == object.id2})
.ToArray();
if(exObjArr.length == 0){
//object does not exist
} else{
//object exists
}

Related

Is an array.forEach with a splice the best way to remove an entry from an array of unique Ids?

I have an array of objects. Each object has a unique userTestrId. Here is the code that I am using when I want to delete one of the objects. Is this the most efficient way I can perform the delete? What I am concerned with is once a row has been deleted the code will still go all the way through the array even though there is no chance of another entry:
var id = 99;
self.tests.forEach(function (elem, index) {
if (elem['userTestId'] === id)
self.tests.splice(index, 1);
});
}
var id = 99;
self.tests.some(function (elem, index) {
if (elem['userTestId'] === id)
self.tests.splice(index, 1);
return true;
});
return false;
}
Could utilise Array.some? Stops looping once you return TRUE from a callback.
This is an alternative to #benhowdle89's answer.
Use Array.prototype.every
The .every method is used to iterate over an array and check whether each and every element passes a test or not. If the callback returns false for any single element, the loop breaks.
Take the following example:
var odds = [3, 5, 7, 9, 11, 12, 17, 19];
//an array with all odd numbers except one
var checkEven = function (n, i, arr) {
console.log ("Checking number ", n);
if (n%2===0) {
arr.splice(i, 1);
return false;
}
return true;
}
console.log(odds.every(checkEven), odds);
If you run the above and look at the console, the loop executed till number 12 only, where it spliced, and stopped.
You can employ similar logic in your code very easily :)
var id = 99;
self.tests.some(function (elem, index) {
if (elem['userTestId'] === id)
self.tests.splice(index, 1);
return true;
});
return false;
}
Polyfill :
some was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of some in implementations which do not natively support it.
// Production steps of ECMA-262, Edition 5, 15.4.4.17
// Reference: http://es5.github.io/#x15.4.4.17
if (!Array.prototype.some) {
Array.prototype.some = function(fun /*, thisArg*/) {
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.some called on null or undefined');
}
if (typeof fun !== 'function') {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++) {
if (i in t && fun.call(thisArg, t[i], i, t)) {
return true;
}
}
return false;
};
}
see in detail
While your concern is technically correct, it's unlikely to be an actual problem(Javascript is fast, this is a microoptimization).
What you should do is focus on using the appropriate interface, so your code could be easy to read and understand. .forEach() does not tell you what you want to do, unless you really do want to do something with each element of the array.
Lodash has the .remove() function, which removes all elements matching a predicate. Unfortunately, I couldn't find the exact specific function you wanted in JS's standard library or in lodash, so you would have to write your own wrapper:
var id = 99
removeFirst(tests, function (elem) { return elem.userTestId === id })
function removeFirst(array, callback) {
var index = array.findIndex(callback)
array.splice(index, 1)
}
Having noted that, you should avoid using an array at all - splicing is way more expensive than looping the whole array to begin with! Instead, since you have a unique identifier, you could use a map:
var map = {}
tests.forEach(function mapper(elem) {
map[elem.userTestId] = elem
})
Now, your removal function is simply delete map[id].

Object Comparing: check if an object contains the whole other object

I have two objects. Their structure looks a bit like this:
{
education: ["school", "institute"],
courses: ["HTML", "JS", "CSS"],
Computer: {
"OS":"WXP",
"WS":"NotePad"
}
}
The second:
{
education: ["school", "university", "institute", "collage"],
courses: ["HTML", "CSS", "JS", "Managing", "Directing"],
Computer: {
"OS":"WXP",
"WS":"NotePad",
"AV":"Avast"
},
something: function(){...},
other: "thing"
}
As you may noticed, the second object containes the whole first object, plus some items that the first one doesn't have.
I need to compare these two objects, and get an answer(true-false) if the second objects containes every single item of the first object.
true - if all of the items of the first object are also in the second one
false - if at least one of the items of the first object is not also in the second one, for example: if the second object wouldn't have the "css" course.
(The first one is requirements, the second is what the person has. I need to check if the person has all of the requirements)
Could be plain JS, jQuery, whatever. I prefer not to use server-side languages for that.
is there a way of doing that?
THANKS!
Just recursively check it:
function isContainedIn(a, b) {
if (typeof a != typeof b)
return false;
if (Array.isArray(a) && Array.isArray(b)) {
// assuming same order at least
for (var i=0, j=0, la=a.length, lb=b.length; i<la && j<lb;j++)
if (isContainedIn(a[i], b[j]))
i++;
return i==la;
} else if (Object(a) === a) {
for (var p in a)
if (!(p in b && isContainedIn(a[p], b[p])))
return false;
return true;
} else
return a === b;
}
> isContainedIn(requirements, person)
true
For a more set-logic-like approach to arrays, where order does not matter, add something like
a.sort();
b = b.slice().sort()
(assuming orderable contents) before the array comparison loop or replace that by the quite inefficient
return a.every(function(ael) {
return b.some(function(bel) {
return isContainedIn(ael, bel);
});
});
JavaScript (in ES5) has two composite native types (I'm assuming you don't have any custom collections in your code, if you do - I assume they support the 'old' iteration protocol (having .length)
Here is an annotated sketch of a solution. I did not run this - it's there to get you an idea of how to implement this algorithm. Note that this enters an endless loop for back references (var a = {}; a.a =a}).
function sub(big,small){
if(typeof big === "function") return small === big; // function reference equality.
if(big.length){ // iterable, for example array, nodelist etc. (even string!)
if(small.length > big.length) return false; // small is bigger!
for(var i = 0; i < small.length; i++ ){
if(!sub(big[i],small[i])){ // doesn't have a property
return false;
}
}
return true; // all properties are subproperties recursively
}
if(typeof big === "object" && big !== null){
// I assume null is not a subset of an object, you may change this, it's conceptual
if(typeof small !== "object" || small === null) return false;
for(var key in small){
// I consider the prototype a part of the object, you may filter this with a
// hasOwnProperty check here.
if(!sub(big[key],small[key])){ // doesn't have a property
return false;
}
return true;
}
}
return big === small; // primitive value type equality
// , or ES7 value type equality, future compat ftw :P
}
Edit: didn't notice that merge changes the first argument... changed the code, but it still would cause obj2 to change. You can add _.cloneDeep(obj2) which should take care of that, but by then my solution doesn't seem as elegant. Updated the demo with cloneDeep as well.
Edit2: Since JSON.stringify requires the order of object properties to be the same in the objects you compare, you could instead use something like Object comparison in JavaScript. However, in the demo you can see that it works, so I would say there is a good chance that for your case, using _.merge with JSON.stringify is reliable.
With lo-dash, you can use _.merge and check whether the result is the same as the larger object.
function(obj1, obj2) {
var obj3 =_.merge(_.cloneDeep(obj2), obj1);
return JSON.stringify(obj3) === JSON.stringify(obj1);
}
demo
Of course, another option would be to iterate over the entire object with vanilla JS.
// When order of objects is not same
function isContainedIn(a, b) {
if (typeof a != typeof b)
return false;
if (Array.isArray(a) && Array.isArray(b)) {
if(a.length == 1) {
var j=0;
while (j < b.length) {
if ((isContainedIn( a[0], b[j]))) {
return true;
}
j++;
}
return false;
} else {
var k=0;
while (k < a.length) {
if (!(isContainedIn([a[k]], b))) {
return false;
}
k++;
}
return true;
}
} else if (Object(a) === a) {
for (var p in a)
if (!(p in b && isContainedIn(a[p], b[p])))
return false;
return true;
} else
return a === b;
};
isContainedIn(requirements, person)
true
In addition to Benjamin's answer - you could test this:
const sub = (big, small) => {
if (typeof big === 'function' || typeof small === 'string') return small === big; // function or string reference equality
if (big && big.length) { // iterable, for example array, nodelist etc. (even string!)
if (small.length > big.length) return false; // small is bigger!
for (let i = 0; i < small.length; i++)
if (!sub(big[i], small[i])) // doesn't have a property
return false;
return true; // all properties are subproperties recursively
}
if (typeof big === 'object' && big !== null) {
// I assume null is not a subset of an object, you may change this, it's conceptual
if (typeof small !== 'object' || small === null) return false;
// console.log(Object.keys(small));
for (const key of Object.keys(small)) {
// I consider the prototype a part of the object, you may filter this with a
// hasOwnProperty check here.
if (sub(big[key], small[key]) === false) // doesn't have a property
return false;
continue;
}
return true;
}
return big === small; // primitive value type equality
};
or even use a much cleaner solution:
https://github.com/blackflux/object-deep-contain

How to delete elements in an array by values without using any external js framework

Yesterday I put the following question:
The best way to remove array element by value
Actually the solution found is not valid because.
Let's suppose this use case:
Array.prototype.deleteElem = function(val) {
var index = this.indexOf(val);
if (index >= 0)
this.splice(index, 1);
return this;
};
var arr = ["orange","red","black","white","red","red"];
var arr2 = arr.deleteElem("red");
arr2 // ["orange","black","white","red","red"]
As you can see this method delets just one entry, and not all of them equal to "red".
How can I fix it?
Maybe with recursion?
Using looping works just as well:
Array.prototype.deleteElem = function (val) {
var index;
while ((index = this.indexOf(val)) !== -1) {
this.splice(index, 1);
}
};
If you have access to the latest version of JavaScript (present in IE>=9 and modern browsers, or shimmed with es5-shim), you can get a new array containing all but that element like so:
var withoutValue = myArray.filter(function (el) { return el !== value; });

Find an item not in array

I have an array of objects that can have up to 6 products in them e.g.
var products = [{name:'Trampoline'}, {name:'Net'}, {name:'Tent'}, {name:'Hoop'}];
// missing Ladder & Anchor
I need a way to check through them, and have it tell me that 'Ladder' and 'Anchor' aren't in the array products. !$.inArray doesn't work (the jquery one).
Can anyone help?? Maybe my brain has just died for the day, cos I just can't figure it out.
I tried starting with an array of all the items it needs, but the first loop through just removes them all becase the first one is not an accessory.
this.getUpsellItem = function() {
var p = this.getProduct();
var slots = ['Net','Tent','Ladder','Basketball','Anchor'];
for(var i = 0; i< p.length; i++) {
if(p[i].display_name2.indexOf('Net') === -1) slots.splice(0,1);
if(p[i].display_name2.indexOf('Tent') === -1) slots.splice(1,1);
if(p[i].display_name2.indexOf('Anchor') === -1) slots.splice(3,1);
if(p[i].display_name2.indexOf('Ladder') === -1) slots.splice(2,1);
if(p[i].display_name2.indexOf('Basketball') === -1) slots.splice(4,1);
console.log(p[i].display_name2.indexOf('Basketball'))
}
console.log('Printing slots')
print_r(slots)
};
Since you're using jQuery we can use the handy jQuery.grep() function to return only the elements in slots that aren't present in products. $.grep takes a function that it uses to filter which elements in the array it should return and which it should discard. In this case we just test each item in slots using products.indexOf. Something like this should suffice:
var slots = [ 'Net', 'Tent', 'Ladder', 'Basketball', 'Anchor' ]
, products = [ { name: 'Trampoline' }, { name: 'Net' },
{ name: 'Tent' }, { name: 'Hoop' }
]
, missing = $.grep(slots, function(product) {
return products.indexOf({ name: product }) < 0 }
)
;
console.log(missing);
Your problem is that you have an array of objects:
var products = [{name:'Trampoline'}, {name:'Net'}, {name:'Tent'}, {name:'Hoop'}];
And you want to search based on a property of these objects. The indexOf method:
compares [...] using strict equality (the same method used by the ===, or triple-equals, operator)
So you won't find what you're looking for unless you have the specific object in hand, just searching based on the property value or an object with the same structure won't work.
jQuery's $.inArray utility function is (AFAIK) just a portability wrapper for JavaScript implementations that don't have an indexOf method in their Array.
You'll need a search function of your own, something like this:
function indexOfByProperty(array, property, value) {
for(var i = 0; i < array.length; ++i)
if(array[i][property] == value)
return i;
return -1;
}
You could also use === if you want to be stricter but that's up to you and what you need the function to do.
If your array is large, you are better off using a map rather than an array
var products = {"Trampoline": {name:'Trampoline'}, "Net": {name:'Net'}, etc..};
products["foo"] returns null
products["Trampoline"] returns {name: 'Trampoline'}
in O(1) time rather than O(n) time
In ES5 you can use Array.some() to drill into nested Objects in an array:
var products = [{name:'Trampoline'}, {name:'Net'}, {name:'Tent'}, {name:'Hoop'}];
var found_ladder = products.some(function(val, idx) {
return val.name === 'Ladder';
});
Javascript in_array function
function in_array (needle, haystack, argStrict) {
// Checks if the given value exists in the array
// * example : in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
// * returns : false
// * example : in_array('van', ['Kevin', 'van', 'Zonneveld']);
// * returns : true
var key = '', strict = !! argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) { return true;}
}
} else {
for (key in haystack) {
if (haystack[key] == needle) { return true; }
}
}
return false;
}

How to determine if object is in array [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 29 days ago.
I need to determine if an object already exists in an array in javascript.
eg (dummycode):
var carBrands = [];
var car1 = {name:'ford'};
var car2 = {name:'lexus'};
var car3 = {name:'maserati'};
var car4 = {name:'ford'};
carBrands.push(car1);
carBrands.push(car2);
carBrands.push(car3);
carBrands.push(car4);
now the "carBrands" array contains all instances.
I'm now looking a fast solution to check if an instance of car1, car2, car3 or car4 is already in the carBrands array.
eg:
var contains = carBrands.Contains(car1); //<--- returns bool.
car1 and car4 contain the same data but are different instances they should be tested as not equal.
Do I have add something like a hash to the objects on creation? Or is there a faster way to do this in Javascript.
I am looking for the fastest solution here, if dirty, so it has to be ;) In my app it has to deal with around 10000 instances.
no jquery
Use something like this:
function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}
return false;
}
In this case, containsObject(car4, carBrands) is true. Remove the carBrands.push(car4); call and it will return false instead. If you later expand to using objects to store these other car objects instead of using arrays, you could use something like this instead:
function containsObject(obj, list) {
var x;
for (x in list) {
if (list.hasOwnProperty(x) && list[x] === obj) {
return true;
}
}
return false;
}
This approach will work for arrays too, but when used on arrays it will be a tad slower than the first option.
Why don't you use the indexOf method of javascript arrays?
Check this out: MDN indexOf Arrays
Simply do:
carBrands.indexOf(car1);
It will return you the index (position in the array) of car1. It will return -1 if car1 was not found in the array.
http://jsfiddle.net/Fraximus/r154cd9o
Edit: Note that in the question, the requirements are to check for the same object referenced in the array, and NOT a new object. Even if the new object is identical in content to the object in the array, it is still a different object.
As mentioned in the comments, objects are passed by reference in JS and the same object can exist multiple times in multiple structures.
If you want to create a new object and check if the array contains objects identical to your new one, this answer won't work (Julien's fiddle below), if you want to check for that same object's existence in the array, then this answer will work. Check out the fiddles here and in the comments.
Having been recently bitten by the FP bug reading many wonderful accounts of how neatly the functional paradigm fits with Javascript
I replicate the code for completeness sake and suggest two ways this can be done functionally.
var carBrands = [];
var car1 = {name:'ford'};
var car2 = {name:'lexus'};
var car3 = {name:'maserati'};
var car4 = {name:'ford'};
var car5 = {name:'toyota'};
carBrands.push(car1);
carBrands.push(car2);
carBrands.push(car3);
carBrands.push(car4);
// ES6 approach which uses the includes method (Chrome47+, Firefox43+)
carBrands.includes(car1) // -> true
carBrands.includes(car5) // -> false
If you need to support older browsers use the polyfill, it seems IE9+ and Edge do NOT support it. Located in polyfill section of MSDN page
Alternatively I would like to propose an updated answer to cdhowie
// ES2015 syntax
function containsObject(obj, list) {
return list.some(function(elem) {
return elem === obj
})
}
// or ES6+ syntax with cool fat arrows
function containsObject(obj, list) {
return list.some(elem => elem === obj)
}
try Array.prototype.some()
MDN Array.prototype.some
function isBiggerThan10(element, index, array) {
return element > 10;
}
[2, 5, 8, 1, 4].some(isBiggerThan10); // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
You could use jQuery's grep method:
$.grep(carBrands, function(obj) { return obj.name == "ford"; });
But as you specify no jQuery, you could just make a derivative of the function. From the source code:
function grepArray( elems, callback, inv ) {
var ret = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
if ( !inv !== !callback( elems[ i ], i ) ) {
ret.push( elems[ i ] );
}
}
return ret;
}
grepArray(carBrands, function(obj) { return obj.name == "ford"; });
I used underscore javascript library to tweak this issue.
function containsObject(obj, list) {
var res = _.find(list, function(val){ return _.isEqual(obj, val)});
return (_.isObject(res))? true:false;
}
please refer to underscore.js documentation for the underscore functions used in the above example.
note: This is not a pure javascript solution. Shared for educational purposes.
You can just use the equality operator: ==. Objects are checked by reference by default, so you don't even need to use the === operator.
try this, just make sure you're using the correct variable reference in the place of car1:
var i, car, l = cars.length;
for (i = 0; i < l; i++)
{
if ((car = cars[i]) == car1)
{
break;
}
else car = null;
}
Edit to add:
An array extension was mentioned, so here's the code for it:
Array.prototype.contains = Array.prototype.contains || function(obj)
{
var i, l = this.length;
for (i = 0; i < l; i++)
{
if (this[i] == obj) return true;
}
return false;
};
Note that I'm caching the length value, as the Array's length property is actually an accessor, which is marginally slower than an internal variable.
I would use a generic iterator of property/value over the array. No jQuery required.
arr = [{prop1: 'val1', prop2: 'val2'}, {prop1: 'val3', prop2: 'val4'}];
objectPropInArray(arr, 'prop1', 'val3'); // <-- returns true
function objectPropInArray(list, prop, val) {
if (list.length > 0 ) {
for (i in list) {
if (list[i][prop] === val) {
return true;
}
}
}
return false;
}
You could try sorting the array based on a property, like so:
carBrands = carBrands.sort(function(x,y){
return (x == y) ? 0 : (x > y) ? 1 : -1;
});
Then you can use an iterative routine to check whether
carBrands[Math.floor(carBrands.length/2)]
// change carBrands.length to a var that keeps
// getting divided by 2 until result is the target
// or no valid target exists
is greater or lesser than the target, and so on, which will let you go through the array quickly to find whether the object exists or not.
try this ,
You can use the JavaScript some() method to find out if a JavaScript array contains an object.
<script>
// An array of objects
var persons = [{name: "Harry"}, {name: "Alice"}, {name: "Peter"}];
// Find if the array contains an object by comparing the property value
if(persons.some(person => person.name === "Peter")){
alert("Object found inside the array.");
} else{
alert("Object not found.");
}
</script>
EDIT 05/18/2022
The most simple way using ES6:
const arrayContainsObject = <T extends Record<string, unknown>>(array: T[], object: T) => {
return array.some(item => Object.keys(item).every(key => item[key] === object[key]))
}
Use like so:
const arr = [{
prop1: 'value1',
prop2: 'value2'
}]
const obj1 = {
prop1: 'value1',
prop2: 'value2'
}
const obj2 = {
prop2: 'value2',
prop1: 'value1'
}
const obj3 = {
prop0: 'value0',
prop1: 'value1'
}
arrayContainsObject(arr, obj1) // true
arrayContainsObject(arr, obj2) // true, even when props are arranged in different order
arrayContainsObject(arr, obj3) // false
Previous answer, don't use (because the order of props in an object needs to be identical)
const arr = [{
prop: 'value'
}]
const obj = {
prop: 'value'
}
arr.some((e) => Object.entries(e).toString() === Object.entries(obj).toString()) // true
i know this is an old post, but i wanted to provide a JQuery plugin version and my code.
// Find the first occurrence of object in list, Similar to $.grep, but stops searching
function findFirst(a,b){
var i; for (i = 0; i < a.length; ++i) { if (b(a[i], i)) return a[i]; } return undefined;
}
usage:
var product = $.findFirst(arrProducts, function(p) { return p.id == 10 });
This function is to check for a unique field.
Arg 1: the array with selected data
Arg 2: key to check
Arg 3: value that must be "validated"
function objectUnique( array, field, value )
{
var unique = true;
array.forEach(function ( entry )
{
if ( entry[field] == value )
{
unique = false;
}
});
return unique;
}
you can use Array.find().
in your case is going to look like this
carBrands.find(function(car){
let result = car.name === 'ford'
if (result == null){
return false;
} else {
return true
}
});
if car is not null it will return the javaScript Object which contains the string 'ford'
The issue with many of the answers here is that they will NOT find an object in an array that is equal to another object. They will only search for an EXISTING object that has a pointer to it in an array.
Quick fix using lodash to see if ANY equal object is in an array:
import _ from 'lodash';
_.find(carBrands, car1); //returns object if true, undefined if false
Working Plunker using this method: https://plnkr.co/edit/y2YX9o7zkQa2r7lJ
if its possible to use es6
carBrands.filter(carBrand => carBrand.name === carX.name).length > 0
if it's true there is a similarity
You can convert both the JSON objects to string and simply check if the bigger json contains the smaller json.
console.log(JSON.stringify(carBrands).includes(JSON.stringify(car1))); // true
console.log(JSON.stringify(carBrands).includes(JSON.stringify(car5))); // false
You could also a the findIndex
var carBrands = [];
var car1 = {name:'ford'};
var car2 = {name:'lexus'};
carBrands.push(car1);
if (carBrands.findIndex(f => f.name === car1.name) === -1) {
console.log('not contain')
} else {
console.log('contain')
}
if (carBrands.findIndex(f => f.name === car2.name) === -1) {
console.log('not contain')
} else {
console.log('contain')
}

Categories

Resources