Array search objects javascript

Check if object value exists within a Javascript array of objects and if not add a new object to array

Is there a way to loop through the array to check whether a particular username value already exists and if it does do nothing, but if it doesn’t to add a new object to the array with said username (and new ID)? Thanks!

Why there’s two elements with the same id ? Is that possible that elements will be removed from this array, or can we be sure that the new element will always have id equal to arr.length + 1 ?

If you don’t want to loop through it, check this Q&A for extending array prototype, stackoverflow.com/questions/1988349/….

native functions are slower compared to normal loops and their support is limited to some browser versions. check my answer below.

22 Answers 22

I’ve assumed that id s are meant to be unique here. some is a great function for checking the existence of things in arrays:

const arr = [< id: 1, username: 'fred' >, < id: 2, username: 'bill' >, < id: 3, username: 'ted' >]; function add(arr, name) < const < length >= arr; const + 1; const found = arr.some(el => el.username === name); if (!found) arr.push(< id, username: name >); return arr; > console.log(add(arr, 'ted'));

Thanks Andy this is a very clean solution to the problem and is working very well. I had not come across the some method before. Your assumption was correct my ID example was just a typo, I was using arr.length + 1 to determine the ID.

Читайте также:  Ссылки социальных сетей html

This small snippets works for me..

const arrayOfObject = [< id: 1, name: 'john' >, ]; const checkUsername = obj => obj.name === 'max'; console.log(arrayOfObject.some(checkUsername)) 

if you have array of elements like [‘john’,’marsh’] then we can do some thing like this

const checkUsername = element => element == 'john'; console.log(arrayOfObject.some(checkUsername)) 

Rather elegant approach! — More details and examples using .some found here — developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

It’s rather trivial to check for existing username:

var arr = [< id: 1, username: 'fred' >, < id: 2, username: 'bill'>, < id: 3, username: 'ted' >]; function userExists(username) < return arr.some(function(el) < return el.username === username; >); > console.log(userExists('fred')); // true console.log(userExists('bred')); // false 

But it’s not so obvious what to do when you have to add a new user to this array. The easiest way out — just pushing a new element with id equal to array.length + 1 :

function addUser(username) < if (userExists(username)) < return false; >arr.push(< id: arr.length + 1, username: username >); return true; > addUser('fred'); // false addUser('bred'); // true, user `bred` added 

It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.

Thanks for this. I went with Andy’s solution in the end because it’s a more succinct way of achieving the same thing. I won’t be removing users at any point so IDs should remain consistent. The check allows users to log in, out and back in again without the array growing overtime. Just for info I’m using this function in conjunction with passport.js and I haven’t been able to find a way of removing users from the array without playing with passport code itself. This solution works nicely.

There could be MULTIPLE POSSIBLE WAYS to check if an element(in your case its Object) is present in an array or not.

let say you want to find an object with >

1. find: It searches for an element in an array and if it finds out then it returns that element else return undefined. It returns the value of the first element in the provided array that satisfies the provided testing function. reference

const ObjIdToFind = 5; const isObjectPresent = arr.find((o) => o.id === ObjIdToFind); if (!isObjectPresent) < // As find return object else undefined arr.push(< id: arr.length + 1, username: 'Lorem ipsum' >); > 

2. filter: It searches for elements in an array and filters out all element that matches the condition. It returns a new array with all elements and if none matches the condition then an empty array. reference

const ObjIdToFind = 5; const arrayWithFilterObjects= arr.filter((o) => o.id === ObjIdToFind); if (!arrayWithFilterObjects.length) < // As filter return new array arr.push(< id: arr.length + 1, username: 'Lorem ipsum' >); > 

3. some: The some() method tests whether at least one element is present in an array that passes the test implemented by the provided function. It returns a Boolean value. reference

const ObjIdToFind = 5; const isElementPresent = arr.some((o) => o.id === ObjIdToFind); if (!isElementPresent) < // As some return Boolean value arr.push(< id: arr.length + 1, username: 'Lorem ipsum' >); > 

Источник

Array.prototype.find()

The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

  • If you need the index of the found element in the array, use findIndex() .
  • If you need to find the index of a value, use indexOf() . (It’s similar to findIndex() , but checks each element for equality with the value instead of using a testing function.)
  • If you need to find if a value exists in an array, use includes() . Again, it checks each element for equality with the value instead of using a testing function.
  • If you need to find if any element satisfies the provided testing function, use some() .

Try it

Syntax

find(callbackFn) find(callbackFn, thisArg) 

Parameters

A function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

The current element being processed in the array.

The index of the current element being processed in the array.

The array find() was called upon.

A value to use as this when executing callbackFn . See iterative methods.

Return value

The first element in the array that satisfies the provided testing function. Otherwise, undefined is returned.

Description

The find() method is an iterative method. It calls a provided callbackFn function once for each element in an array in ascending-index order, until callbackFn returns a truthy value. find() then returns that element and stops iterating through the array. If callbackFn never returns a truthy value, find() returns undefined .

callbackFn is invoked for every index of the array, not just those with assigned values. Empty slots in sparse arrays behave the same as undefined .

find() does not mutate the array on which it is called, but the function provided as callbackFn can. Note, however, that the length of the array is saved before the first invocation of callbackFn . Therefore:

  • callbackFn will not visit any elements added beyond the array’s initial length when the call to find() began.
  • Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
  • If an existing, yet-unvisited element of the array is changed by callbackFn , its value passed to the callbackFn will be the value at the time that element gets visited. Deleted elements are visited as if they were undefined .

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The find() method is generic. It only expects the this value to have a length property and integer-keyed properties.

Examples

Find an object in an array by one of its properties

const inventory = [  name: "apples", quantity: 2 >,  name: "bananas", quantity: 0 >,  name: "cherries", quantity: 5 >, ]; function isCherries(fruit)  return fruit.name === "cherries"; > console.log(inventory.find(isCherries)); // 

Using arrow function and destructuring

const inventory = [  name: "apples", quantity: 2 >,  name: "bananas", quantity: 0 >,  name: "cherries", quantity: 5 >, ]; const result = inventory.find(( name >) => name === "cherries"); console.log(result); // 

Find a prime number in an array

The following example finds an element in the array that is a prime number (or returns undefined if there is no prime number):

function isPrime(element, index, array)  let start = 2; while (start  Math.sqrt(element))  if (element % start++  1)  return false; > > return element > 1; > console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found console.log([4, 5, 8, 12].find(isPrime)); // 5 

Using find() on sparse arrays

Empty slots in sparse arrays are visited, and are treated the same as undefined .

// Declare array with no elements at indexes 2, 3, and 4 const array = [0, 1, , , , 5, 6]; // Shows all indexes, not just those with assigned values array.find((value, index) =>  console.log("Visited index", index, "with value", value); >); // Visited index 0 with value 0 // Visited index 1 with value 1 // Visited index 2 with value undefined // Visited index 3 with value undefined // Visited index 4 with value undefined // Visited index 5 with value 5 // Visited index 6 with value 6 // Shows all indexes, including deleted array.find((value, index) =>  // Delete element 5 on first iteration if (index === 0)  console.log("Deleting array[5] with value", array[5]); delete array[5]; > // Element 5 is still visited even though deleted console.log("Visited index", index, "with value", value); >); // Deleting array[5] with value 5 // Visited index 0 with value 0 // Visited index 1 with value 1 // Visited index 2 with value undefined // Visited index 3 with value undefined // Visited index 4 with value undefined // Visited index 5 with value undefined // Visited index 6 with value 6 

Calling find() on non-array objects

The find() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .

const arrayLike =  length: 3, "-1": 0.1, // ignored by find() since -1 < 00: 2, 1: 7.3, 2: 4, >; console.log(Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x))); // 7.3 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Polyfill of Array.prototype.find in core-js
  • Indexed collections
  • Array
  • Array.prototype.findIndex()
  • Array.prototype.findLast()
  • Array.prototype.findLastIndex()
  • Array.prototype.includes()
  • Array.prototype.filter()
  • Array.prototype.every()
  • Array.prototype.some()
  • TypedArray.prototype.find()

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Оцените статью