Home > Mobile >  Why empty string is not getting appended in the map?
Why empty string is not getting appended in the map?

Time:10-28

const strs = ["eat", "tea", "tan", "ate", "nat", "bat"]

var sortAlphabets = function(text) {
  return text.split('').sort().join('');
};

let map = new Map();
for (let str of strs) {
  let key = sortAlphabets(str);
  map[key] = [...map[key] || "", str];
}

console.log(
  Object.values(map)
)

if I add any string lets say "te" the map looks like this

map[key]=[...map[key] || "te" , str];

Map(0) {   
    aet: [ 't', 'e', 'eat', 'tea', 'ate' ], 
    ant: [ 't', 'e', 'tan', 'nat' ],  
    abt: [ 't', 'e', 'bat' ]
    }

and when it is empty map[key]=[...map[key] || "" , str];

Map(0) {
    aet: [ 'eat', 'tea', 'ate' ],
    ant: [ 'tan', 'nat' ],
    abt: [ 'bat' ]}

So why is empty string not getting added in the map?

CodePudding user response:

I really don´t understand what you want to do, but I think that this may solve your question. This code is trying to iterate string value you're passing, if you want to take it like literal empty value, you have to put it like value inside array. This make than when it be iterated, the value returned will be any string inside. To have empty value try only wrapping ''(empty value) inside array [''] like this:

strs = ["eat","tea","tan","ate","nat","bat"]
var sortAlphabets = function(text) {
    return text.split('').sort().join('');
};
let map = new Map();
for (let str of strs) {
    let key = sortAlphabets(str);
    map[key] = [...map[key] || [''], str];

}
console.log( map )

CodePudding user response:

I did not fully understand the problem, but it is not correct to use map objects like this. Get and set must be used for the map object.

Like that:

const strs = ["eat", "tea", "tan", "ate", "nat", "bat"]

var sortAlphabets = function(text) {
  return text.split('').sort().join('');
};

let map = new Map();
for (let str of strs) {
  let key = sortAlphabets(str);
  map.set(key, "te");
}

CodePudding user response:

You have problem in line:

  map[key] = [...map[key] || [''], str];

you spread table or just pust talbe with empty string. so after first interation in map[key] you have array [['']].

fix:

const strs = ["eat", "tea", "tan", "ate", "nat", "bat"]

var sortAlphabets = function(text) {
  return text.split('').sort().join('');
};

let map = new Map();
for (let str of strs) {
  let key = sortAlphabets(str);
  map[key] = [...(map[key] || []), str];
}

console.log(
  Object.values(map)
)

if you need add empty string to each key just:

 map[key] = [...(map[key] || ['']), str];
  • Related