Suman Basnet
Suman Basnet

Reputation: 75

How to swap one array element with its respective next array element and display output?

Here I created hashmap array and created one function.

var rule = 
{
"c": "d",
"a": "o",
"t": "g",
"h": "a",
"1":"@",
"e": "n",
"n": "t"
}
function convert(str) {
return [...str].map(d => rule[d]).join('')
}
console.log(convert("cat1hen"))

It display output as "dog@ant".But I want different output.Everytime there is expected output as "@",I want to swap "@" to swap its value with next array element.

It means output should be "doga@nt" instead of "dog@ant".Here position of @ is swapped with its next array element i.e "a". The position should be swapped only when expected output is "@".

Upvotes: 0

Views: 65

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50664

You can add a second argument to you .map() call for the index (i) and then swap the values if @ occurs:

See code comments for further details:

var rule = {
  "c": "d",
  "a": "o",
  "t": "g",
  "h": "a",
  "1": "@",
  "e": "n",
  "n": "t"
}

function convert(str) {
  let strArr = [...str];
  return strArr.map((d, i, arr) => {
    if (rule[d] == '@') { // If current letter maps to '@'
      return rule[arr[i + 1]]; // Set the current letter to the next one 
    } else if (rule[arr[i - 1]] == '@') { // If the previous letter mapped to '@'
      return '@'; // Set the current letter to the '@' SAME AS: return rule[strArr[i - 1]]
    }
    return rule[d];
  }).join('')
}
console.log(convert("cat1hen"))

Upvotes: 2

Related Questions