0

In the below code his._notifications is an array of objects, each object contains the properties shown below.

What I am trying to do is to check if each object not passed to the function func() was pushed into the array or not?

So I am using .find() and I expect it returns true if the object was passed to the function or if it already exists in the array, and false otherwise.

But the below log statement prints undefined! Why isExists is undefined? And what is the recommended way to check if an item is duplicate or not in an array?

code:

func(noti)
const isExists = this._notifications.find((obj) =>
  obj.title === noti.safeTitle
  && obj.text === noti.safeText
  && obj.bannerTitle === noti.safeBannerTitle
  && obj.bannerText === noti.safeBannerText
  && obj.icon === noti.icon
  && obj.onClickCallback === noti.onClickCallback
  && obj.eNotificationType === noti.notificationType
  && obj.deleteable === noti.deletable
  && obj.withBanner === noti.withBanner
);
logger.info('[isNotificationExists] For the current notification: ', JSON.stringify(notification), ' isExists: ', isExists);
k0pernikus
  • 60,309
  • 67
  • 216
  • 347
Amrmsmb
  • 1
  • 27
  • 104
  • 226

2 Answers2

1

From MDN

The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.

The includes() method determines whether an array includes a certain element, returning true or false as appropriate. It uses the sameValueZero algorithm to determine whether the given element is found.

To check if an item is duplicated in array

function hasDuplicates(array) {
  return (new Set(array)).size !== array.length;
}
Community
  • 1
  • 1
Hyyan Abo Fakher
  • 3,497
  • 3
  • 21
  • 35
  • is there a recommended way how to check if an entry is duplicate in the array or not – Amrmsmb Jul 10 '18 at 12:48
  • 2
    If you want to check for duplicates in an Array, that question has probably been asked on the site already. If the answers to that/those question(s) don't meet your needs then consider asking a new one; but be prepared to explain why the existing answer(s) don't meet your requirements. – David Thomas Jul 10 '18 at 12:50
-1

find() is not a suitable data structure here as it's return type is the element found not the flag(that whether it was found of not). You can use underscorejs _.contains functions for this.

http://underscorejs.org/#contains

Zain Mohsin
  • 97
  • 1
  • 11