Locating if a certain string in an array is even or odd in JavaScript

I am currently on a mission to locate an odd string within a given array.

Here's the code:

const friendArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"];

function findOddString(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].length % 2 !== 0) {
      return arr[i];
    }
  }
}
const mysteriousFriend = findOddString(friendArray);
console.log(mysteriousFriend);

Answer №1

This example demonstrates how to filter out odd elements from an array of friends:

const friendList = ["alice", "bob", "charlie", "dave", "eve", "frank",];

function filterOddFriends(friendList) {
  if (friendList.length % 2 !== 0) {
    return friendList;
  }
}

const myOddFriends = friendList.filter(filterOddFriends);
console.log(myOddFriends);

Answer №2

.flatMap() combined with a ternary callback creates a concise and easy-to-read filter function. It may not be completely clear whether you intended to filter only odd-length strings or both odd and even lengths, so here are both versions:

Strings with Odd Lengths

const fArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"];

let odd = fArray.flatMap(o => o.length % 2 === 1 ? [o] : []);

console.log(odd);

Strings with Odd & Even Lengths

const fArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"];

let oe = [[], []];

fArray.forEach(o => o.length % 2 === 1 ? oe[0].push(o) : oe[1].push(o));

console.log(oe);

Answer №3

If you're looking to extract all the odd-length friends from an array, you can utilize the Array.filter() method. This function will generate a new array containing only those friends whose length meets the specified condition.

// Given array of friends
const friendArray = ["agdum", "bagdum", "chagdum", "lagdum", "jagdum", "magdum"];

// Extracting odd-length friends
console.log(friendArray.filter((friend) => friend.length % 2 !== 0));

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

The functionality of reordering columns, virtual scrolling, and resizing the grid in jqgrid are not functioning properly

Implementing jqgrid with Symfony to display a datagrid has been a challenging task for me. Thanks to Oleg's insightful response, many of the major issues have been resolved. Below is a snippet of my code: <link rel="stylesheet" type="text/css" ...

Showing the value of a JavaScript variable within an HTML input field

Here is an interesting HTML structure that includes a list and input field: <li> <span>19</span> </li> <li> <span>20</span> </li> ...

Unbind a prepared statement in a node.js environment using SQL

Utilizing the node-mssql library (https://github.com/patriksimek/node-mssql) and encountered a problem when attempting to execute a second request, resulting in the following error: this.connection.pool.acquire(done); ^ TypeEr ...

What is the procedure for adding a data table to an HTML table with JSON?

I'm trying to display a table fixture layout in an HTML table using the Ajax method, but it's not working. I'm not sure what the problem is. Can someone please help me out with my code? Controller JsonResult public JsonResult FixturesVal( ...

Creating a conditional statement in jQuery that will append text to a specific DIV element after a form has been successfully

I currently have a form set up that is functioning properly, but I am looking to make some changes. Instead of redirecting the user to a new page with a success message upon submitting the form, I want the success message to be displayed in a div next to t ...

Revise my perspective on a modification in the backbone model

I am new to using Backbone and I am currently practicing by creating a blog using a JSON file that contains the necessary data. Everything seems to be working, although I know it might not be the best practice most of the time. However, there is one specif ...

The style attribute is triggering an error stating that 'Every child in a list must possess a distinct "key" property.'

Can anyone explain why I'm encountering an error when storing JSX code in a variable like this? const centerStyle = {textAlign: 'center'}; viewState.myContent = ( <Fragment> <p style={centerStyle}>Some text</p> < ...

Create a Promise that guarantees to reject with an error

I am relatively new to utilizing promises, as I typically rely on traditional callbacks. The code snippet below is from an Angular Service, but the framework doesn't play a significant role in this context. What really matters is how to generate a pro ...

Attempting to modify the Nivo slider configuration has proven to be ineffective

Can someone assist me in getting the Nivo Slider to function properly? I keep receiving a "syntax error" on the last line and can't seem to figure out what's causing it. The error occurs specifically on the line that reads: " }); " which is the ...

Exploring a One-dimensional Array

I have successfully conducted a search in the array. Now I'm looking for a way to display the location of the searched value within the array using the code below. import javax.swing.*; import java.util.Arrays; public class Listahan { public st ...

The issue of Next.JS fetch not caching data within the same request

I am faced with a straightforward setup where a Next.JS server-side component is responsible for fetching and displaying a post. The challenge lies in setting the page title to reflect the title of the post, requiring me to call my posts API endpoint twice ...

Issue - The command 'bower install' terminated with Exit Status 1

During my journey through the angular-phonecat tutorial, a frustrating error popped up right after I executed the npm install command: I even checked the log file, but it just echoed the same error message displayed in the console. What's the piece o ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

React returns Not a Number when summing up numbers

On the cart page, I am calculating the total for each product. Each object contains quantity and price which are multiplied to get the total value of the product. However, since users can have multiple products in their cart, I need to sum the totals of ...

Using three.js to create a rotating analog clock in Javascript

I currently have a traditional clock displayed in my setting that I want to synchronize with the current time. I am able to keep the clock running by calculating each hand's rotation every second, but I am encountering peculiar issues with the minute ...

The NVD3 tooltip is being obscured by other divs

Attempting to make the NVD3 tooltip appear above all other divs has presented a challenge. With three charts lined up horizontally and tooltips that exceed the boundaries of their divs, adjusting the z-index creates a dilemma. Regardless of which side&apos ...

Issue encountered with edges helper and a partly opaque object rendering

My goal is to create a realistic earth using three.js, similar to this example, which is an improvement from this one. However, I am facing an issue where the rendering order of the sky, earth, and atmosphere is not being properly interpreted by the render ...

Experiencing problems with the calling convention in JavaScript

Here is a snapshot of the code provided: If the function testFields at Line:3 returns false, then the program correctly moves to Line:21 and returns the value as false. However, if testFields returns true, the program proceeds to Line:4, but instead of ex ...

What sets apart a space after the ampersand from no space in Material UI?

Could you clarify the difference between using a space after the ampersand compared to not having a space? For example: Why is there a space after the ampersand in & label.Mui-focused but no space in &.Mui-focused fieldset? const WhiteBorderTextF ...

Divide a collection of q promises into batches and execute them sequentially

In order to achieve my objective of copying files while limiting the number of files copied in parallel based on a defined variable, I decided to divide an array of promises using calls to fs.copy into packets. These packets are then executed in series by ...