discovering the absence of any letters within an array

Looking for a way to find multiple missing letters in an array? Check out this code snippet:

function missingLetters(str) {
  var nums = str.split('').map(function(letter){
    return letter.charCodeAt();
  })
  
  var result = [];
  
  for(var i=0; i<nums.length - 1; i++){
    if(nums[i+1] - nums[i] >1){
      for(var j = nums[i]+1 ; j< nums[i+1]; j++){
        result.push(String.fromCharCode(j));
      }
    }
  }
  
  return result;
}

missingLetters("abceghj");

This revised code will loop through every element in the array and return an array of all missing letters between existing ones.

Answer №1

Instead of immediately returning, it is recommended to store the values in an array or string and return them at the end

function findMissingLetter(str) {
  var characters = str.split('').map(function(letter){
    return letter.charCodeAt();
  })
  const missingLetters = [];
  for(var i=0; i<characters.length; i++){
    if(characters[i+1] - characters[i] >1){
      missingLetters.push(String.fromCharCode(characters[i]+1))
    }
  }
  return missingLetters
}

console.log(findMissingLetter("abcegi"));

Answer №2

Instead of returning each letter individually from the function, it is recommended to return an array or string as a whole

function findMissingLetters(str) {
  var missingLetters = [], charCodes = str.split('').map(function(letter){
    return letter.charCodeAt();
  })
  
  for(var i=0; i<charCodes.length; i++){
    if(charCodes[i+1] - charCodes[i] >1){
      missingLetters.push(String.fromCharCode(charCodes[i]+1))
    }
  }
  return missingLetters
}

console.log(findMissingLetters("abce"));
console.log(findMissingLetters("abceghj"));

If you need a more robust solution that can handle duplicates and letters in the wrong order, check out Marcus' implementation here: https://codepen.io/marcusparsons/pen/YYxrpG

Answer №3

In order to return a collection of values, you must use either an array or a string as you can't return multiple values at once. One way to achieve this is by modifying your function to store the found values in an array.

function findMissingLetters(str) {
  var result = [];
  var letters = str.split('').map(function(char){
    return char.charCodeAt();
  });

  for (var i = 0; i < letters.length; i++) {
    if(letters[i + 1] - letters[i] > 1) {
      result.push(String.fromCharCode(letters[i]+1));
    }
  }
  return result;
}

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

Randomizing a playing card set until achieving a particular value

I am struggling with a new project where I need to shuffle a deck of cards, draw the first four cards, and calculate the total sum of those cards. Although I have completed this task successfully, my challenge now is to repeat this process until the sum to ...

Tips for maintaining the same identifier, content, or text despite changes in the DOM

I am curious about a situation where the ID of a div is changed from 1 to 34, but when clicked on, the attribute still returns 1 instead of 34. I apologize for any language errors, thank you. $(document).on('click','.edit_btn:eq(0)& ...

Can the conventional HTML context menu be swapped out for a link context menu instead?

Currently, I am working on developing a custom linkbox component that is similar to the one found on this page: Here is an example of the code: export const Linkbox = ({}) => { const linkRef = useRef(null); return ( // eslint-disable-next-l ...

What is the process for including a scope in an Angular.js HTTP controller?

I am looking to access a $scope variable within this controller in order to utilize Angular functions like ng-click and ng-change in my HTML. Currently, I am only able to use the $http function but unable to execute any Angular methods on it. I am struggli ...

Utilize a Google Chrome extension to interact with the DOM of the active tab

Alright, so I've got a good grasp on JavaScript/jQuery and can use them for various tasks. However, my current challenge involves manipulating the DOM of the open tab. I'm curious to know if it's feasible or if all the actions performed by a ...

Animating CSS with jQuery for a background image effect

I have the following JavaScript code : $(".linksColl a li").hover(function () { $(this).css({ "background-image" : "url(images/links/linkHover1.png)", "background-position" : "center center", ...

The error message "THREE is not defined" occurred while running mocha tests for a

I am attempting to execute a basic Mocha unit test for code that utilizes the Vector3 class from THREE.js: import {Vector3} from 'three'; const a = new Vector3(0, 0, 0); When running this test using Mocha (specifically mocha-webpack, with webpa ...

Sending data retrieved asynchronously to child components' props

Currently, I am developing an application that fetches an array of news items from a remote source and showcases them on a webpage. After successfully calling the endpoint using $.getJSON(), as indicated by console logs, I integrated this call into the pa ...

What is the reason behind unhandled promise rejections?

Whenever I send a post request using Postman to localhost:5000/api/profile/experience, I keep receiving these warnings: UnhandledPromiseRejectionWarning: ValidationError: Profile validation failed: experience.0.title: Path `title` is required., experience ...

Using a function as a parameter in a React component constructor

I have a question about a snake game I'm developing using React. After reading a post on Stack Overflow discussing setting functions inside the constructor, I am facing an issue with calling a function (foodGenerator) from within another function (sn ...

What could be causing the .text method to not retrieve text even when it is present?

Currently experimenting with web scraping using Selenium to extract the color of a particular dress. Despite finding the text content under the 'screen-reader-text' class when inspecting the website, my attempts at fetching it result in an empty ...

Is there a way for my code to detect when a function and a timeout are in progress?

Is there a way to disable my button after just one click, or when the timeOut function is running? Currently, I have code that allows the button to be clicked only if my moneyValue is greater than money, and it's working perfectly. Now, within that sa ...

Show the JSON data from the server in a table format

Is there a way to neatly display data received from an Ajax response within a table format? Below is the structure of the table: <table data-toggle="table" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" id="menu_table"> ...

Utilizing HTML/CSS (with Bootstrap): Reveal the concealed <input type="color"> color selector by clicking on a different HTML component

Is there a way to trigger a color picker from a hidden <input type="color"> by clicking on another HTML element, like a <span>? While this functionality seems to work on Firefox, it consistently fails on Chromium. Are there any cross- ...

What is the process for changing and updating the key of an object based on comparisons with other objects?

My task involves working with an array of objects that contain unique IDs as keys. const sampleObj1 = {0011:[{},{}], 0022:[{}, {}], 0033:[{},{}]} const sampleObj2 = [{id:0011, name:'test1'}, {id:0022, name:'test2'}, {id:0033, name:&apos ...

How to download a dynamically generated PHP file to your local machine

I am trying to find a solution where the search results can be downloaded by the user and saved on their computer. Currently, the file is automatically stored on the server without giving the user an option to choose where to save it. In the search form, ...

Securing Routes with Firebase User Authentication in ReactJS

Currently, I am encountering an issue with the auth.onAuthStateChanged function in my Firebase user authentication service integrated with ReactJS. The function fires after the component has already been rendered, causing problems with redirecting users to ...

I am experiencing difficulty with Three.js rendering textures from my planet constructor function

I am facing an issue with my function that is supposed to create a 3D object (a planet) using orbital parameters and texture images from a dataset. Strangely, the textures are not rendering when I use StandardMaterial or PhongMaterial, even though they wor ...

Encountering a Node.js issue when attempting to properly sanitize data before inserting it into MySQL

This is a snippet of code that I am using to insert data into a MySQL table. Before running the query, I escape the values like so: const mysql = require('mysql'); const R = require('ramda'); class Repository { constructor(connectio ...

Jade Compilation with Gulp

Currently utilizing gulp-jade, I have encountered an error with a particular template: 557| 558| > 559| 560| .tabs-wrap(ng-show="eventExists"): .contain-center 561| 562| #room-tabs-contain.contain-disable.contain: .contain-center unexpec ...