Inspecting every element within an array and indicating a negative outcome if any item is not a string

I'm currently working on a function called 'every' that takes in an array and a callback function as arguments. The purpose of the callback function is to determine if all elements in the array meet a certain condition. In my case, I want the function to return true if all elements are strings, and false otherwise.

Here is what I have so far:

function every(myArray, callback) {
  var myNewArray = [];
  for (var i = 0; i < myArray.length; i++){
    var added = callback(myArray[i]);
    myNewArray.push(added);
  }
  if (myArray === 'string') {
    return true;
  } else {
    return myNewArray
  }
}

function isTrueOrFalse(string) {
  if (typeof string === 'string') {
     return true;
  } else {
    return false;
  }
}
var result = every(
  ['5','test true','truthy statement','stringy'],
  isTrueOrFalse
);
console.log(result);

As it stands now, the function returns a boolean value for each element in the array: 'false', 'true', 'true', 'true'

However, I only want it to return one false and stop there. What am I missing?

Answer №1

There is no need to create a new array in the every function. Instead, focus on checking the callback's return value. If it returns false, immediately return false. Otherwise, at the end of the loop, return true.

function every(myArray, callback) {
  for (var i = 0; i < myArray.length; i++) {
    if (!callback(myArray[i])) {
      return false;
    }
  }
  return true;
}

function containsString(string) {
  return typeof string === 'string';
}
var result = every(['5', 'test true', 'truthy statement', 'stringy'], containsString)
console.log(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

Creating a simulation of a JavaScript callback within a C# host program

Currently, I am in the process of developing a c# application with an embedded web browser control. In this project, I'm facing a challenge where I need to call a C# method from JavaScript and pass a JavaScript callback using the dynamic technique exp ...

Establishing the null values for input parameters

Whenever the button is clicked, I want to reset the input values to null. The function spremi() gets triggered when the button is clicked, but I want to set the values of podaci.tezina and podaci.mamac back to their initial values so that the user can en ...

unable to call the anonymous inline onclick method of JavaScript

In my HTML file, I have the following code: <a onclick="getRestaurantTime({{ $afternoonTiming[$j]->id}});">Hello</a> Furthermore, I have an anonymous function in restaurant.js file: var Restaurant = (function ($) { function getRestaur ...

What is the best way to ensure my buttons hide or display correctly when clicked?

I have been working on setting up an edit button that toggles the visibility of save and cancel buttons. However, I encountered a problem where all the buttons disappear when I click on the edit button. This issue did not occur with my other buttons, and t ...

qunit timer reset

I have developed a user interface for manually launching qunit tests. However, I have noticed that the qunit test timer starts when displaying the interface, rather than when starting the actual test. For example: var myFunction = function (){ test ...

Vue application experiencing never-ending update cycle following array assignment

Here is the JavaScript code I am working with: const storage = new Vue({ el: '#full-table', delimiters: ['[[', ']]'], data: { events: [], counter: 0, }, methods: { eventCounter: fu ...

Error message: The function pokemon.map does not exist

I'm new to learning react and I've been working on creating a react app using the pokemon API. However, I've encountered an error that says TypeError: pokemon.map is not a function. I'm unsure why .map is not recognized as a function in ...

What is the best way to retrieve the value of a checkbox element in React.js when submitting a form?

Whenever I try to submit a form, I encounter an issue where I am unable to retrieve the value of the checked boxes (I don't mean the check value but the actual value attribute of the HTML element). Here is an example of my element in the parent compo ...

Ways to determine if a new set of input values duplicates previous rows in an array

My form has an array of input fields. Is there a way to validate each row's inputs and ensure that they all have at least one unique value in any field, preventing identical rows? For example, the 2nd row should only be allowed to have a maximum of ...

Capture locations from Google Maps

What is the best method to extract all addresses, along with their latitude and longitude, for a specific city (such as Bangalore) from Google Maps using PHP/JavaScript and store it in a MySQL table? I urgently need assistance. Thank You ...

Using .on as a substitute for live will not yield the desired results

I've been aware for some time now that the .on method is meant to replace .live, but I just can't seem to get it working. I've attempted: $(this).on('click', function(){ // Do something... }) $(this).on({ click: function ...

Issue: React child must be a valid object - Runtime Error Detected

As I delve into the world of React, NextJs, and TypeScript, I stumbled upon a tutorial on creating a navbar inspired by the 'Strip' style menu. It has been quite a learning journey for me as a newbie in these technologies. After seeking help for ...

What steps can I take to minify my code using react-create-app?

Currently, I am facing an issue with minifying my code on the server. Despite running npm run build, which is supposed to handle all the minifying processes (as shown here: https://i.stack.imgur.com/wjpd7.png), I still see the unminified code when accessin ...

Having Trouble with Your React.js Rendering?

I'm starting to learn React.js but I'm having trouble rendering it into the HTML. I can't figure out what's wrong. Any help would be greatly appreciated. Below are the HTML and JSX code: (Note: Full links to the react library are incl ...

Exploring the capabilities of dynamic pathname routing in Next.js

Consider this scenario: there is a path that reaches me as /example/123 and I must redirect it to /otherExample/123. My code utilizes next/router, extracting the URL from router.asPath. if(router.asPath == '/example/123') { Router.push(' ...

Using both CASE and MATCH operators within an array in Neo4j's Cypher Query Language (

Using the code snippet below, I am attempting to retrieve all details related to user data where the checked value is either 1 or 0. I have noticed that 'WHERE flight.checked IN check' does not seem to be properly working. Is it appropriate to u ...

Create text that alternates between blinking and changing content simultaneously

I'm currently working on a website and I am curious about how to achieve the effect of making text blink and change content simultaneously, similar to what is seen on this particular website . Sorry for not being more specific in my question. Thank yo ...

Learn the process of synchronously loading forms and data in Angular

Looking to synchronize the loading of data and form... Let's start by reviewing the code: ngOnInit() { if (this.data.fromCalendar) { this.singleTraining(); } }, 200); this.formControl(); } formControl() { this.gib ...

Do iframes not utilize parental jquery?

I have a homepage that utilizes jQuery by loading it from the ajax google APIs in the head> tag. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js" type="text/javascript"></script> I attempted to use jQuery functions ...

I recently started delving into React Native and am currently exploring how to implement custom fonts in my application. However, I have encountered an error that is preventing me from successfully integrating

The Issue: The error I encountered only appeared after including font-related code (such as importing from "expo-font" and using "AppLoading" from "expo", and utilizing the "Font.loadAsync()" function). Error: Element type is invalid: expected a string (fo ...