Get non existing element from array in javascript

javascript array find index
find object in array javascript
javascript find index of object in array by property
javascript array filter
javascript array contains
javascript map
find key in array javascript
javascript array includes not working

I have two arrays

var a = [{'Id': 1, 'name':'bob', 'age':22}, {'Id': 2, 'name':'alice', 'age':12}, {'Id': 3, 'name':'mike', 'age':13}, {'Id': 4, 'name':'prasad', 'age':25}];
var b = [{'Id': 1, 'name':'bob', 'age':22}, {'Id': 2, 'name':'alice', 'age':12}, {'Id': 3, 'name':'mike', 'age':13}];

I want to compare each element of array a with array b based on ID (Ids are unique always) and want only record which present in array a but not in array b

Here expected output would be

{'Id': 4, 'name':'prasad', 'age':25}

What I have tried so far:

for (var elementA of a) {
    var uniqueElement = true;
    for (var elementB of b) {
         //if condition chekcs elementA.Id and elementB.Id
         //setting values
    }
}

I believe there will be elegant approve to solve this?

Try following. Create a Set of Ids of b array and then filter array a based on that.

CASE 1: Use Array.filter in case of more than 1 entry

var a = [{'Id': 1, 'name':'bob', 'age':22}, {'Id': 2, 'name':'alice', 'age':12}, {'Id': 3, 'name':'mike', 'age':13}, {'Id': 4, 'name':'prasad', 'age':25}];
var b = [{'Id': 1, 'name':'bob', 'age':22}, {'Id': 2, 'name':'alice', 'age':12}, {'Id': 3, 'name':'mike', 'age':13}];

var objB = b.reduce((a,c) => a.add(c.Id), new Set());

var result = a.filter(v => !objB.has(v.Id));
console.log(result);

Array.prototype.find(), Array elements which do not pass the callback test are simply skipped, and If existing elements of the array are changed, or deleted, their value as been popped off `words` before filter can even get there // ["spray" ,"limit"]  Get the last few elements in the array. You can use the same technique to slice the array starting from the end of it. Pretty cool.

With ES6:

const idsFromB = b.map(item => item.Id)
const c = a.filter(item => idsFromB.indexOf(item.Id) < 0)
//outputs [{'Id': 4, 'name':'prasad', 'age':25}]

Array.prototype.filter(), When accessing a non-existing object property, JavaScript returns undefined . trying to get data from the non-existing property value. first : element inserted at the beginning of array  Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person [0] returns John: var person = ["John", "Doe", 46]; Try it Yourself » Objects use names to access its "members". In this

var a = [{ 'Id': 1, 'name': 'bob', 'age': 22 }, { 'Id': 2, 'name': 'alice', 'age': 12 }, { 'Id': 3, 'name': 'mike', 'age': 13 }, { 'Id': 4, 'name': 'prasad', 'age': 25 }];
var b = [{ 'Id': 1, 'name': 'bob', 'age': 22 }, { 'Id': 2, 'name': 'alice', 'age': 12 }, { 'Id': 3, 'name': 'mike', 'age': 13 }];

const na = [];

a.filter((_a) => {
    let isNotUnique = true;
    for (var elementB of b) {
        if (_a.Id === elementB.Id) {
            isNotUnique = false;
            break;
        }
    }
    
    if (isNotUnique) {
        na.push(_a);
    }
    
});

console.log(na);

Array.prototype.indexOf(), If it finds an array element where the function returns a true value, find() returns the value of that array element (and does not check the remaining values)  Therefore: callback will not visit any elements added to the array after the call to find begins. If an existing, yet-unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time find visits that element's index. Elements that are deleted are still visited.

This is essentially a set difference problem.

var a = [
  {'Id': 1, 'name':'bob', 'age':22},
  {'Id': 2, 'name':'alice', 'age':12},
  {'Id': 3, 'name':'mike', 'age':13},
  {'Id': 4, 'name':'prasad', 'age':25}
];
var b = [
  {'Id': 1, 'name':'bob', 'age':22},
  {'Id': 2, 'name':'alice', 'age':12},
  {'Id': 3, 'name':'mike', 'age':13}
];

console.log(JSON.stringify(diff(a, b), null, 2));

function diff(a, b) {
  return a.filter(x => !b.some(y => deepCompare(x, y)));
}

// https://stackoverflow.com/a/1144249/1762224
function deepCompare(){var t,e,r,n;function o(t,e){var f;if(isNaN(t)&&isNaN(e)&&"number"==typeof t&&"number"==typeof e)return!0;if(t===e)return!0;if("function"==typeof t&&"function"==typeof e||t instanceof Date&&e instanceof Date||t instanceof RegExp&&e instanceof RegExp||t instanceof String&&e instanceof String||t instanceof Number&&e instanceof Number)return t.toString()===e.toString();if(!(t instanceof Object&&e instanceof Object))return!1;if(t.isPrototypeOf(e)||e.isPrototypeOf(t))return!1;if(t.constructor!==e.constructor)return!1;if(t.prototype!==e.prototype)return!1;if(r.indexOf(t)>-1||n.indexOf(e)>-1)return!1;for(f in e){if(e.hasOwnProperty(f)!==t.hasOwnProperty(f))return!1;if(typeof e[f]!=typeof t[f])return!1}for(f in t){if(e.hasOwnProperty(f)!==t.hasOwnProperty(f))return!1;if(typeof e[f]!=typeof t[f])return!1;switch(typeof t[f]){case"object":case"function":if(r.push(t),n.push(e),!o(t[f],e[f]))return!1;r.pop(),n.pop();break;default:if(t[f]!==e[f])return!1}}return!0}if(arguments.length<1)return!0;for(t=1,e=arguments.length;t<e;t++)if(r=[],n=[],!o(arguments[0],arguments[t]))return!1;return!0}
.as-console-wrapper { top: 0; max-height: 100% !important; }

7 Tips to Handle undefined in JavaScript, No new elements will be added. Merging (Concatenating) Arrays. The concat() method creates a new array by merging (concatenating) existing arrays: Example​  Array.from() has an optional parameter mapFn, which allows you to execute a map() function on each element of the array being created. More clearly, Array.from(obj, mapFn, thisArg) has the same result as Array.from(obj).map(mapFn, thisArg), except that it does not create an intermediate array.

var c;

a.forEach((aobj) => {
c = 0;
b.forEach((bobj) => {
if (aobj.Id === bobj.Id) {
  c++;
 }
})
 if (c === 0) console.log(aobj);
})`

JavaScript Array find() Method, isset() does not return TRUE for array keys that correspond to a NULL value, while to take the performance advantage of isset() while keeping the NULL element Well, and you get this warning three times (on the bools and the float, but not  An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned. Description. If the specified number of elements to insert differs from the number of elements being removed, the array's length will be different at the end of the call. Examples

JavaScript Array Methods, In JavaScript, and just like many other languages out there, at some point To remove a particular element from an array in JavaScript we'll want to first find the the index for the first occurrence of the given value, or -1 if it is not in the array. See the Pen JavaScript - Get the first element of an array- array-ex-3 by w3resource (@w3resource) on CodePen. Improve this sample solution and post your code through Disqus. Previous: Write a JavaScript function to clone an array. Next: Write a JavaScript function to get the last element of an array. Passing a parameter 'n' will return the

array_key_exists - Manual, Here's a Code Recipe to check if a #JavaScript array contains a value. Taking that concept, we can also use it to compare object element in an array like this: All other indices we can get of indexOf() will give you a truthy (non-zero) value  Neither the length of a JavaScript array nor the types of its elements are fixed. Since an array's length can change at any time, and data can be stored at non-contiguous locations in the array, JavaScript arrays are not guaranteed to be dense; this depends on how the programmer chooses to use them.

Remove Element from an Array in JavaScript, The find () method executes the function once for each element present in the array: If it finds an array element where the function returns a true value, find () returns the value of that array element (and does not check the remaining values) Otherwise it returns undefined. Note: find () does not execute the function for empty arrays.

Comments
  • Could be done using one liner: a.find(elA => !b.find(elB => elB.Id === elA.Id))
  • Thank you all for your overwhelming response, I will try each and every suggestions. It would be great if you help me with explanation as I am new to typescript, javascript too
  • @Prasadtelkikar there's not even one answer written in TS :)
  • @ponury-kostek, good catch.. I updated my comment.. Solutions are working like a charm..Cheers
  • If only single object is expected then Array#find could be used instead of Array#filter. Good use of Set ;)
  • @Rayon - Agreed. I will update the answer covering both the scenarios. Thanks!
  • I tried this one working as expected.. Thanks Nikhil
  • More readable and easy to understand. I tried this as well.. working as expected. but sorry I can accept only one answer... Cheers