Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double for loop in Javascript inner array length

Tags:

javascript

I am trying to create a function that takes in a string and changes each letters value to a "(" if the character is not duplicated in the string, and a ")" if the character does have a duplicate present in the string. I have decided to go an unconventional route to solve this problem but I am running in to an issue with a double for loop. From what I understand, the inner for loop in javascript does not have access to the variables outside of the loop. I want to loop through every item in an array twice but I'm not sure what to set the inner loops length as.

Here is my code:

function sortAndChange(word) {
const splitter = word.toLowerCase().split("");
//let jSplitter = word.toLowerCase().split("").length;
let endResult = "";
let truthArray = [];

for(i = 0; i < splitter.length; i++){
    for(j = 0; j < splitter.length; j++){
        console.log(j);
        if(splitter[i] == splitter[j]){
            truthArray.push(true);
        } else {
            truthArray.push(false);
        }
    }
    console.log(truthArray);
    truthArray.every(item => item === false) ? endResult += "(" : endResult += ")";
    truthArray = [];
}
console.log(endResult);
}

Expected Result:

sortAndChange("Success") //expected output: ")())())"
sortAndChange("easy") //expected output: "(((("
like image 262
klaurtar1 Avatar asked Dec 15 '25 15:12

klaurtar1


2 Answers

You can do that in following steps:

  • Convert string to array using split and use map() on it.
  • Compare the indexOf() and lastIndexOf() to check if its duplicate or not.
  • Return the ) or ( based on ur condition. And then at last join the array

function sortAndChange(str){
  let arr = str.toLowerCase().split('')
  return arr.map(x => {
    //if its not duplicated
    if(arr.indexOf(x) === arr.lastIndexOf(x)){
      return '('
    }
    //If its duplicated
    else{
      return ')'
    }
  }).join('');
}

console.log(sortAndChange("Success")) //expected output: ")())())"
console.log(sortAndChange("easy")) //expected output: "(((("
like image 61
Maheer Ali Avatar answered Dec 17 '25 05:12

Maheer Ali


You could take a object and keep a boolean value for later mapping the values.

This approach has two loops with O(2n)

function sortAndChange(word) {
    word = word.toLowerCase();
    var map = [...word].reduce((m, c) => (m[c] = c in m, m), {});
    return Array
        .from(word, c => '()'[+map[c]])
        .join('');
}

console.log(sortAndChange("Success")); // )())())
console.log(sortAndChange("easy"));    // ((((
like image 27
Nina Scholz Avatar answered Dec 17 '25 05:12

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!