JavaScript - Employing the .every function with an array containing objects

Is it possible to use the array.every method on multidimensional arrays?

The structure of my array is as follows:

tabs=[
{label: string, icon: icon, routerLink: link},
{label: string, icon: icon, routerLink: link},
{label: string, icon: icon, routerLink: link}]

I am trying to determine if every LABEL within tabs is different from a specific label. I would appreciate a detailed explanation since I am new to programming and keen on understanding the process! But any answer is welcome. :) Thank you in advance!

EDIT: I am using the following method to add Tabs to my Tabmenu(ng2, primeng):

addTab(id: string) {
  if (id === 'linechart') {
    this.tab = {
      label: 'NW-Details',
      icon: 'fa-area-chart',
      routerLink: ['/nwdetails']
    }
    TABS.push(this.tab);
  }
  if (id === 'piechart') {
    this.tab = {
      label: 'IO-Details',
      icon: 'fa-pencil',
      routerLink: ['/iodetails']
    }
    TABS.push(this.tab)
  }
}

Whereas TABS is typeof MenuItem[] provided by primeng, tab is any.

Whenever I double-click on a chart, this function is called and a new tab is added to my menu. Now I want to check if a tab with a certain label is already open to prevent opening it again. I have tried using for loops combined with if statements

for (i = 0; i < TABS.length; i++) {
  if (TABS[i].label !== 'NW-Details') {
    this.tab = {
      label: 'NW - Details',
      icon: 'fa - area - chart'
      TABS.push(this.tab)
    }
  }

However, this results in opening a new tab each time it is not equal, causing multiple tabs to be opened upon double-clicking when there are existing tabs.

Answer №1

If you're looking for a solution, consider utilizing the Array#every method.

tabls.every(function(item){
  return item.label !== targetValue
})

To learn more about the behavior of Array#every, refer to the official MDN documentation:

The every method applies the provided callback function to each element within the array until it encounters one where the callback returns a falsy value (a value that is false when converted to Boolean). If such an element is found, the method will promptly return false. Conversely, if the callback returns a true value for all elements, the method will return true. Callback is only triggered for array indexes with assigned values and will not apply to deleted or unassigned indexes.


Alternatively, you can also consider using the Array#some method

!tabls.some(function(item){
  return item.label === targetValue
})

For more insights on the functionality of Array#some, you can consult the MDN documentation here:

The some() method will execute the callback function for each element in the array until it discovers an element where the callback returns a truthy value (a value that is true when converted to Boolean). Upon finding such an element, the method will immediately return true. If not, it will return false. Callback is invoked only for array indexes with assigned values and will not apply to deleted or unassigned indexes.

Answer №2

Array functions have a signature that typically looks like this:

Array.prototype.functionName = function(callback){
  for (var i = 0; i< this.length; i++){
    if(callback(this[i]))
      // do something.
    else
      // do something.
  }
}

A callback function is expected to return a boolean value, either true or false.

every vs some

While both every and some can be used in a similar way, it is important to use them in a way that accurately conveys the intended meaning.

var d = [1,2,3,4,5];
var valid = d.every(function(num){ return !isNaN(num); });
console.log(valid)

The above code signifies "valid if all elements are numbers". Using .some instead would change the meaning to "invalid if anyone is not a number". Choose the method based on the context of the code to enhance readability.

References

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

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

Design a custom Bootstrap dropdown using an input[type="text"] element

After exploring the Bootstrap dropdown example here, I realized that for my particular scenario, it would be more beneficial to have an input field (type="text") instead of a button. This way, I can display the selected option from the dropdown. Is there ...

Remove console.log and alert statements from minified files using uglifyjs-folder

Currently, I am minifying multiple files in a directory using the uglifyjs-folder feature within my npm configuration in the package.json file as shown below: "uglifyjs": "uglifyjs-folder js -eyo build/js" The process is effectively minifying all the fil ...

Submitting form by double clicking and pressing enter at the same time

When using jQuery Validate to validate forms, I encounter a problem where double-clicking the submit button results in my application making two entries with the same data. This issue also occurs when pressing enter multiple times. Despite researching dif ...

The appearance of HTML varies depending on the type of mobile device being used

My email template is having display variations on different mobile devices, with the textbox sometimes centered instead of left aligned as intended. Any suggestions on what might be causing this issue and how to resolve it? Desired Display on All Devices ...

Develop a scrambled PHP webpage for a CAPTCHA system

I've implemented the cool-captcha feature in my registration form. Here's the code snippet that generates the Captcha image: <img src="captcha.php" id="captcha" /> However, there is an issue where anyone can easily access the "captcha.ph ...

Manipulating DropDownList Attributes in ASP.NET using JavaScript

I am facing an issue with populating a Dropdownlist control on my ASCX page. <asp:DropDownList ID="demoddl" runat="server" onchange="apply(this.options[this.selectedIndex].value,event)" onclick="borderColorChange(this.id, 'Click')" onblur="bo ...

What are the consequences of relying too heavily on deep type inference in React and Typescript?

In the process of migrating my React + Javascript project to Typescript, I am faced with preserving a nice unidirectional flow in my existing code. The current flow is structured as follows: 1. Component: FoobarListComponent -> useQueryFetchFoobars() 2 ...

Utilizing jQuery UI autocomplete with AJAX and JSON data sources

I've been facing an issue with the jQuery UI autocomplete feature, and despite extensive research, I have only managed to partially resolve it. The code below is what I'm currently using to make it work: $("#term").autocomplete({ source: fun ...

Tips for setting an argument with a promise data type

I am currently working on writing unit tests using jest to test two functions in a separate file called generator, where I generate fake data : generator.ts export async function generateReportData(overide = {}) { return { clientId: faker.data ...

Looking to organize an array of objects containing two string elements (countries) based on the country name using TypeScript or the Lodash library?

Below is an example of an array of objects I am working with: { countries: [{ "country_alpha2_code": "PW", "country_name": "PALAU" },{ "country_alpha2_code": "US&qu ...

Stop the observable interval in Angular when the route changes

I initiated an interval in an Angular component, but the requests are still being made even when I navigate to a different route. How do I halt the interval? //function that returns an observable getAllPolls() { return Observable.interval(2000).swit ...

Send the ID of the checkbox to a PHP file using AJAX

Is it possible to generate a network graph by selecting checkboxes? When I choose one or more checkboxes and click the button, I expect to see a network graph with the selected checkboxes. It almost works, but when I select multiple checkboxes, only one ...

Limit access to route in ExpressJS only to internal redirects

I'm managing an ExpressJS application that includes specific routes which I intend to only function when redirected to from my code, rather than input directly into the URL. Essentially, if a user attempts to enter "myapp.com/url" it should not be ac ...

Ways to combine values from various arrays

Currently, my FedEx shipping calculator works well for shipping a single item. However, there are times when I need to ship multiple items at once. Here's the code snippet: $xyz=calcShip(30,4,4,2.5); foreach ($xyz as $sType => $tCost){ print $ ...

I'm wondering why my socket.io emit isn't triggering a content update

While working on adapting the IBM angularjs tutorial here into a Yeoman angular-fullstack tutorial, I encountered a slight issue. In my version, when I vote on a Poll, the data does not refresh to display the results. I have tried extensively debugging it ...

The Ajax request fails to send the form files

I'm encountering an issue where a form isn't passing one variable. Here is my table structure: Schema::create('projects', function(Blueprint $table) { $table->increments('id'); $table->string(&apos ...

How to selectively make properties optional in Typescript conditions

Currently, I am working on creating a utility type to unwrap nested monads of Options in my code. Here is the progress I have made so far: export interface Option<T> { type: symbol; isSome(): boolean; isNone(): boolean; match<U>(fn: Mat ...

Router-view failing to display component

I am currently working on setting up basic routing in Vue. I have identified three file listings that seem to be causing issues. When I include <router-view> in app.vue, the foo component appears in the browser. However, when I follow the instruction ...

Designing functions with HTML

I have been working on creating a Coffeescript function that incorporates common HTML for an object that is frequently used on my page. To make the content dynamic, I am passing a variable to the function which will be replaced each time it is called. Unfo ...