Calculate the difference to obtain a whole number from the overall length of the array [JavaScript]

Here is the code I am working with:

function likes(names) {
  if (names.length == 0) {
    return 'no one likes this';
}  else if (names.length >= 4) {
    return names[0]+ ', ' + names[1] + ' and' + names.length - 2 + 'others like this';
}  else if (names.length <4 && names.length >0){
return names[0] + ', ' + names[1] +' and ' + names[2] +' like this'
}}

The issue I am facing is in line number 5. I am trying to subtract 2 from the length of the array and add it to the string, but my approach seems to be incorrect. If anyone has any suggestions on how to achieve this, your help would be greatly appreciated. Thank you!

Answer №1

To ensure the numeric subexpression is not included in the larger string concatenation process, surround it with parentheses:

return names[0]+ ', ' + names[1] + ' and ' + (names.length - 2) + ' others like this';

This approach allows the numeric subtraction subexpression to be evaluated independently, resulting in its concatenation into the string.

Answer №2

In contrast to Pointy's solution, I find template strings to be more elegant:

const output = `${names[0]}, ${names[1]} and ${names.length - 2} others are fans of this`;

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

AngularJS directive failing to trigger event binding within the link function

Here is a plunker that you can refer to. In my project, I have developed two simple element directives, named incButtonOne and incButtonTwo. These directives are designed to track and display the number of times they have been clicked. Each directive has ...

When using Selenium to locate an element, it appears to be returning an unexpected empty object

This question has been bothering me for quite some time. I am currently using Selenium in conjunction with Python to find an element within a webpage. The specific element I am targeting is as follows: <a id="topmenu_adhocQtraditional_Reports" ...

`Interact with images to display toggled information using a combination of CSS and JavaScript

Is there a way to make the images on my portfolio clickable so that more information about the project appears on the first click, and then hides when clicked again? Preferably using simple JavaScript without jQuery. I found a website where this feature i ...

What is the best way to extract information from a JSON object?

I am currently utilizing the JSON.js library provided by JSON.org. <% JSONReturn = GetDistance(Sample) // this function returns a string in JSON format (specifically from the ArcGIS server Solve Route function) JSONObject = JSON.parse(JSONReturn,"Tota ...

What could possibly be the issue with my PHP variables?

My PHP script uses a python script to retrieve new data. While I am successfully able to loop through and extract key2 and value2 from an array using foreach, I am facing issues with extracting the variables $address and $product to include in a $shell com ...

Total of all the values within an array

//Calculating the total sum of elements in an array and displaying it #include<iostream> using namespace std; int main() { int n; cout << "Enter the number of Elements in an array: "; cin >> n; int a[n]; fo ...

Problem with Ionic App crashing

Currently, I am developing an Ionic app that relies on local storage for offline data storage. The app consists of approximately 30 different templates and can accommodate any number of users. Local storage is primarily used to store three key pieces of i ...

The router should display a component based on the user's access level, even if they are

I'm working on a scenario where the home route needs to cater to both admin and user roles. Is there a way to dynamically display the UserComponent if logged in as a user, and show the AdminComponent if logged in as an admin? This is my current setup ...

RxJs will only consider the initial occurrence of a specific type of value and ignore any subsequent occurrences until a different type of value is encountered

I'm faced with a situation where I need to extract the first occurrence of a specific value type, followed by the next unique value of a different type. Let's break it down with an example: of(1,1,1,1,2,3,4) .pipe( // some operators ) .subsc ...

The evaluation of jQuery did not function properly on the less.css file

I have a jQuery function that I am using as shown below @winheight:`$(window).height()` within my less file. However, when I compile it to CSS, I encounter a compiler error I am currently using a software called Crunch Compiler Errors You are usin ...

Help setting up Angular ng-class is needed

Hey there, I'm currently attempting to change the background color of my CSS based on the value of ng-class (true or false). Can someone help me out with this? <div id="home"> Summoner <div id="in ...

Utilizing JQuery Template to Invoke JavaScript Functions

If I have the following JSON object structure: ITEMS is an array with one element, and FILTER is another array with 3 items in it. Description: "churches with some restrictions" ITEMS: {...} [0]: {...} FILTER: {...} ...

Strange Scrolling Issues in Blackberry Webworks when Using Touchscreens

Within my Blackberry Webworks app designed for Smartphones OS 6, 7, and 7.1, there is a portion of code that looks like this: <div style="width:100%; height:100%; overflow:hidden;"> <div style="overflow:auto;height:100px;width:100%;"> ...

Prevent cross-site scripting (XSS) when using vue toasted for displaying notifications

Whenever I include js code like "><img src=1 onerror=prompt(document.cookie);> in an input field and click submit, I use vue-toasted. The notification appears as shown in this image: https://i.sstatic.net/Gju9h.jpg and a popup shows the cookie in ...

Maximizing the potential of a cell in a table

I am currently using AJAX to retrieve and display data in my table. However, I want to capture the actual value from the selected cell in the table. To better display user needs, I have split the returned value to obtain specific items. Below is the scri ...

What is the best way to implement a nested lookup in MongoDB within a field?

Within my database, I have a collection named Randomhospital. Inside this collection, there is a field named hospital structured as follows: { "id": "GuDMUPb9gq", "Hospital Name": "UPHI", "Hospital City&qu ...

The variable "tankperson" is not recognized

While attempting to run an AJAX request upon page load, I encountered a particular error even though I have ensured that all the necessary libraries are included. The variable tankperson is derived from $_GET['name'] An unhandled ReferenceErr ...

Guide to building a react-redux application with a Node server as the backend

Hey there! I'm looking to build a react-redux app with a node server as the backend. Is it feasible for the node server to serve the react-redux app instead of having react-redux run on one port and node on another? Any suggestions on how to kick thi ...

Steps for concealing a div element upon clicking on it

Is there a way to create an accordion where all the tabs start off closed, but open when clicked and close when clicked again? I have managed to open one tab, but I am struggling to figure out how to close it and how to make the opening and closing process ...

Is it better to load AngularJS partials at the start instead of waiting until they are needed in Django?

In my Django project, I have a template folder where all the templates and partials for my app are stored. Instead of loading each partial individually based on controller requests in Angular, I want to preload all the partials into the template cache at t ...