惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

C
Check Point Blog
AI
AI
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
Vercel News
Vercel News
Stack Overflow Blog
Stack Overflow Blog
P
Proofpoint News Feed
Microsoft Security Blog
Microsoft Security Blog
The GitHub Blog
The GitHub Blog
WordPress大学
WordPress大学
Martin Fowler
Martin Fowler
博客园 - 【当耐特】
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
F
Full Disclosure
Google DeepMind News
Google DeepMind News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Help Net Security
Recorded Future
Recorded Future
N
News and Events Feed by Topic
雷峰网
雷峰网
V
Vulnerabilities – Threatpost
Schneier on Security
Schneier on Security
aimingoo的专栏
aimingoo的专栏
S
Schneier on Security
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
O
OpenAI News
Project Zero
Project Zero
罗磊的独立博客
G
GRAHAM CLULEY
腾讯CDC
P
Privacy International News Feed
V
V2EX
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
H
Heimdal Security Blog
L
LINUX DO - 热门话题
Forbes - Security
Forbes - Security
美团技术团队
MongoDB | Blog
MongoDB | Blog
Security Latest
Security Latest
M
MIT News - Artificial intelligence
T
Tor Project blog
Cisco Talos Blog
Cisco Talos Blog
宝玉的分享
宝玉的分享
T
Threat Research - Cisco Blogs
TaoSecurity Blog
TaoSecurity Blog

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Checking if an Array Contains a Value in JavaScript
Dmitri Pavlutin · 2020-07-21 · via Dmitri Pavlutin Blog

JavaScript offers a bunch of useful array methods to check whether an array contains a particular value.

While searching for primitive value like number or string is relatively easy, searching for objects is slightly more complicated.

In this post, you will read about how to determine if an array contains a particular value, being a primitive or object.

1. Array contains a primitive value

A primitive value in JavaScript is a string, number, boolean, symbol, and special value undefined.

The easiest way to determine if an array contains a primitive value is to use array.includes() ES2015 array method:


const hasValue = array.includes(value[, fromIndex]);


The first argument value is the value to search in the array. The second, optional, argument fromIndex is the index from where to start searching. The method returns a boolean indicating whether array contains value.

For example, let's determine whether an array of greeting words contains the values 'hi' and 'hey':


const greetings = ['hi', 'hello'];

greetings.includes('hi'); // => true

greetings.includes('hey'); // => false


greetings.includes('hi') returns true because the array contains 'hi' item.

But greetings.includes('hey') returns false, denoting that 'hey' is missing in the greetings array.

1.1 Searching from an index

array.includes(value, fromIndex) also accepts an optional second argument to start search for value starting an index.

For example, let's start searching from the second item (index 1 and up) in the array:


const letters = ['a', 'b', 'c', 'd'];

letters.includes('c', 1); // => true

letters.includes('a', 1); // => false


letters.includes('c', 1) starts searching for 'c' letter from index 1. As expected, the letter is found.

However, letters.includes('a', 1) returns false because the array from index 1 until the end doesn't contain the item 'a'.

2. Array contains an object

Checking if an array contains an object is slightly more complex than searching for primitive values.

Determining if an array contains a reference to an object is easy — just use the array.includes() method. For example:


const greetings = [{ message: 'hi' }, { message: 'hello' }];

const toSearch = greetings[0];

greetings.includes(toSearch); // => true


greetings.includes(toSearch) returns true because the greetings array contains toSearch object reference (which points to the first item of the array).

But more often, instead of searching by reference, you'd like to search for objects by their content. In such a case array.includes() won't work:


const greetings = [{ message: 'hi' }, { message: 'hello' }];

const toSearch = { message: 'hi' };

greetings.includes(toSearch); // => false


greetings.includes(toSearch) returns false, because the array doesn't contain toSearch object reference. Although the array contains the object hi that looks exactly like toSearch.

Ok, so how do you determine if the array contains an object by content, rather than reference? Using array.some() method in combination with shallow or deep equality check of objects.

During shallow equality check of objects the list of properties of both objects is checked for equality.

Here's a possible implementation of shallow equality check:


function shallowEqual(object1, object2) {

const keys1 = Object.keys(object1);

const keys2 = Object.keys(object2);

if (keys1.length !== keys2.length) {

return false;

}

for (let key of keys1) {

if (object1[key] !== object2[key]) {

return false;

}

}

return true;

}


shallowEqual(object1, object2) returns true in case if both compared objects object1 and object2 have the same set of properties with the same values.

In the following code snippet hi and hiCopy are equal by content, while hi and hello are not:


const hi = { message: 'hi' };

const hiCopy = { message: 'hi' };

const hello = { message: 'hello' };

shallowEqual(hi, hiCopy); // => true

shallowEqual(hi, hello); // => false


As a reminder, the array method array.some(callback) returns true if at least one time callback function returns true.

Now, let's use the shallow equality function in combination with array.some(callback) method to find if the array contains an object by content:


const greetings = [{ message: 'hi' }, { message: 'hello' }];

const toSearch = { message: 'hi' };

greetings.some(item => shallowEqual(item, toSearch)); // => true


greetings.some(item => shallowEqual(item, toSearch)) checks every item of the array for shallow equality with toSearch object.

If the searched object contains also nested objects, then instead of shallowEqual() function you could use the deepEqual() function.

3. Summary

Searching for a primitive value like string or number inside of an array is simple: just use array.includes(value) method.

Determining if an array contains an object by content needs more moving parts. You have to use array.some(callback) method combined with shallow equality check:


array.some(item => shallowEqual(item, value));


Note that the presented approaches are not the only ones. E.g. for a long time array.indexOf(value) !== -1 expression (which is slighlty clumsy) has been used to determine if the array contains value.

What other ways to detect if an array contains a value do you know?