Search code examples
javascriptarrayssortingcomparisoncounter

How can I check if a character of a string is already a element of an array?


With a string, ex: data. I want to insert all new characters in an array, respecting the example I gave the answer should be:

characters = ["d","a","t"];

I did the following up to now:

const balanced = string => {
  var characters = [];
  var characters_Counter = 0;
  
  for (var i = 0; i < string.length; i++) {
    if (string.charAt(i) != characters){
      characters[characters_Counter] = string.charAt(i);
      characters_Counter++;
    }
    
    console.log(characters[i]);
  }
  
};

In the if I want to compare string.charAt(i) with all the elements inside characters[] and if it is a new character do the if's content. The problem is: I'm stuck, I can't think a way to make this comparison work.


Solution

  • Use the includes() method to check if an element (character) is inside an array

    const balanced = string => {
      var characters = [];
      var characters_Counter = 0;
    
      for (var i = 0; i < string.length; i++) {
        if (!characters.includes(string.charAt(i))) {    // <------ here
          characters[characters_Counter] = string.charAt(i);
          characters_Counter++;
          console.log(characters[i]);
        }
      }
    
    };
    
    balanced("data");