Reputation: 69
// exmaple is passed
// strings = ["sun", "bed", "car"] n = 1 //["car", "bed", "sun"]
// strings = ["abce", "abcd", "cdx"] n = 2 //["abcd", "abce", "cdx"]
function solution(strings, n) {
let arr = [];
let obj = {};
/* before
for(let i = 0; i < strings.length; i++) {
obj[strings[i].slice(n)] = strings[i]
}
*/
// after
for(let i = 0; i < strings.length; i++) {
if (Object.keys(obj).includes(strings[i].slice(n))) {
obj[strings[i].slice(n) + 1] = strings[i]
} else obj[strings[i].slice(n)] = strings[i]
let temp = Object.keys(obj).sort()
let x = 0
while(x < temp.length) {
arr.push(obj[temp[x]])
x++
}
return arr
To summarize the code
I thought of the code in this way, but please give me some advice on where it went wrong.
LINK URL : https://programmers.co.kr/learn/courses/30/lessons/12915?language=javascript#
> My result I don't know the parameters of the test case
Upvotes: 0
Views: 73
Reputation: 350310
Your approach will not work when the letter that becomes the key
is not unique, you will overwrite that entry in your obj
object, which will lead to an output that has fewer items than the input.
It will be easier to use the sort
method directly, putting the logic in the callback function:
function solution(strings, n) {
return [...strings].sort((a, b) => (a[n]+a).localeCompare(b[n]+b));
}
console.log(solution(["sun", "bed", "car"], 1));
console.log(solution(["abce", "abcd", "cdx"], 2));
Upvotes: 1