Top method to verify if a specific coordinate exists within an array (JavaScript)

When working with arrays of coordinates, viewed as arrays of length 2, it becomes necessary to verify if a certain coordinate is included in that array. However, JavaScript doesn't offer a straightforward way to do this (even when using the ES2016 method Array.includes or the older Array.indexOf, you'll encounter the same issue):

const a = [[1,2],[5,6]];
const find = a.includes([5,6]);
console.log(find);

This code snippet returns false. This has always been a point of confusion for me. Could someone please explain why it returns false? To workaround this limitation, I typically create a helper function:

function hasElement(arr,el) {
     return arr.some(x => x[0] === el[0] && x[1] === el[1])
}

The condition inside can also be replaced by x.toString() === el.toString(). Utilizing this approach, hasElement(a,[5,6]) will indeed return true.

Is there a more elegant solution for checking inclusion, preferably without resorting to writing additional helper functions?

Answer №1

If you want to search for a specific array within another array in JavaScript, you can use the JSON.stringify method. This method allows you to convert the javascript object or value to a JSON string. Once you have both arrays converted to strings, you can simply check if the main array includes the array you are searching for.

const a = [[1,2],[5,6]], array = [5,6];
const find = JSON.stringify(a).includes(JSON.stringify(array));
console.log(find);

Answer №2

One key reason is that when it comes to JavaScript, arrays are essentially objects and cannot be compared as simple values. Since two object instances will always remain unique, even if they appear identical visually, they are still considered separate entities and hence never equate to each other. For instance:

console.log([8, 9] === [8, 9]) // returns false

The Array class in JavaScript is a fundamental global object utilized for creating arrays; which serve as list-like, high-level objects.

Answer №3

To simplify your code, you can utilize the find method along with destructuring.

const numbers = [
  [1, 2],
  [5, 6]
];

const targetNumbers = [5, 6];

// Approach 1
const findNumber = numbers.find(numArr => numArr.every(val => targetNumbers.includes(val)));

// Approach 2
const [targetX, targetY] = targetNumbers;
const findNumber2 = numbers.find(([x, y]) => targetX === x && targetY === y);

console.log(findNumber, findNumber2);

Answer №4

Looking back at the response from Siva K V, to locate the index of the initial instance in the array where this condition holds true, you can simply swap out find with findIndex (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)

const a = [
  [1, 2],
  [5, 6]
];

const target = [5, 6];

// Approach 1
const find = a.findIndex(x => x.every(y => target.includes(y)));

// Approach 2
const [xt, yt] = target;
const find2 = a.findIndex(([x, y]) => xt === x && yt === y);

console.log(find, find2);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding data from one object to another in Javascript results in duplicated entries

Despite my efforts to find a solution for my issue, I couldn't locate a relevant topic. Being new to Javascript, I suspect my lack of understanding is hindering me from resolving the problem. After days of trying, I'm still unable to grasp it. An ...

The FindProxyForURL function in a pac (proxy-auto-config) file is not compatible with the IE browser

After struggling for three days, we are still unable to solve a peculiar technical issue and now seek your assistance. The PAC (Proxy Auto-Config) file we have created works flawlessly in all browsers except for Internet Explorer (IE). The URL in questio ...

What is the best way to retrieve the name of a product with its switch or toggle turned on within a parent div using Cypress?

I have a specific test case that I need to run, but I'm unsure how to incorporate an if condition into it. This is the parent div HTML code. <div class="row collection-listing pro-list-collection"> <div class="col-md-3 add-a- ...

The mysterious problem of an undefined event in the Revealing Pattern in JavaScript

Struggling with my use of the modular design pattern for JS and encountering issues with arguments bound functions. I have a function that I want to bind to different events to avoid repetitively writing it out for each event. The only difference in the fu ...

Struggling to modify a JSON value within a loop

I am currently developing a JavaScript code that involves updating one JSON based on conditions from another JSON. Below is the code I have written. const a = [{ "a": "Not Started" }, { "b": "Not Started" }, { "c": "Not Started" }, { "d": "Not S ...

Connection error: API is down

The current issue I am facing with the application I'm developing is that it is not responding with the API address for weather data. Despite getting a response from Ajax, the specific weather API I am trying to call remains unresponsive. I have exha ...

Maintaining the order of subscribers during asynchronous operations can be achieved by implementing proper synchronization

In my Angular setup, there is a component that tracks changes in its route parameters. Whenever the params change, it extracts the ID and triggers a function to fetch the corresponding record using a promise. Once the promise resolves, the component update ...

Guide on extracting the content of tables from the <td> tags based on the value in the <th> tag

I have a large table in HTML that looks like this: <table id="selectTerminals" size="35"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Full Name</th> ...

Reimagining scrolling through content with a stylish unordered list (a sleek alternative to a select box

After having our company website redesigned by a professional designer, our site now looks much more visually appealing. However, I have encountered difficulties when trying to implement their design using HTML and CSS. One particular challenge is the heav ...

Guide on how to incorporate an external javascript file into an HTML button

I am currently working on an exercise through Udacity that involves creating an HTML form with JavaScript functions. The task is to input text into the form, submit it, and have it displayed on the webpage within a blue square. This exercise is designed to ...

Placing an anchor around a div extends its clickable area beyond the div

Just starting out with programming and I'm running into a problem where the anchor is clickable outside of my div. The div includes a sliding tab from the right displaying a randomly generated film, and ideally the entire tab should be clickable to d ...

What options do I have for sorting through my inventory using the search feature?

Having some trouble setting up isotope filtering on my search bar. I have managed to get the Isotope function working on checkboxes, but for some reason, my search bar isn't functioning as expected. I found a solution online for filtering results bas ...

Connect the element in the array to a specific identifier in a different object

I'm currently facing an issue while trying to create a report page using the code below. I am encountering difficulties in accessing equivalent array values from the objItems[i] object which results in a "Uncaught TypeError: Cannot read properties of ...

The lightbox emerges from the bottom of the screen

Currently, I am attempting to incorporate lightbox2 () into my WordPress theme after finding that all other plugins were ineffective. However, the lightbox is opening below the page content on my test blog (), forcing users to scroll down. If anyone has i ...

The procedure of Change Detection and the specific moment when OnPush properties are verified

According to a source, Angular performs 14 operations when checking for changes. But at what specific moment does it verify if the component has ChecksEnabled set to false (OnPush), and especially, when does it check if any @Input properties have changed i ...

Ways to activate the input focus event within a method in Vue.js

With an input that has the following event implemented: <b-nput class="input" id="link" v-model="link" placeholder="link" @focus="$event.target.sel ...

Error in jQuery and Canvas Image Crop: The index or size is invalid, exceeding the permissible limit

Recently, I downloaded and installed the Canvas Image Crop plugin from CodeCanyon but encountered a problem specifically on firefox. An error message kept popping up whenever I tried to upload certain images: "Index or size is negative or greater than the ...

How can you create an array using results from a MySQL query?

How can I convert a MySQL query into an array format? This is how the array should be structured: <?php $testLocs = array( '1' => array( 'info' => '1. New Random info and new position', 'lat' => 453 ...

What is the best way to utilize AJAX to send a value from a foreach loop in Laravel?

I'm encountering an issue where all forms are sending the value as if it's from the first form, however, my intention is for each form to send the data inside it when I press the send button. Blade @foreach($car_lists as $car_list) <li class= ...

What is the best way to send information from child components to their parent in React

I'm facing a scenario where I need to increase the parent value based on actions taken in the children components. Parent Component: getInitialState :function(){ return {counter:0} }, render(){ <CallChild value={this.state.counter}/> ...