Home > Software design >  kth largest element(string) in an array based on length
kth largest element(string) in an array based on length

Time:12-05

I need to find the kth largest element in an array(of strings) and return them according to the rank.

Example -

Input

var array = ['java','python','javascript','C','Swift','Dart'];

Expected Output

[['javascript', 1],
 ['python', 2],
 ['Swift', 3],
 ['java', 4],
 ['Dart', 4],
 ['C', 5]]

I tried this -

var rank = 0
var result = []
var arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a,b)=>b.length-a.length);
for(let i=0;i<arr.length;i  ){
        if(arr[i 1]===undefined){
            break;
        }
        else if (arr[i].length>arr[i 1].length){
          rank} 
       result.push([arr[i],rank])
}
console.log(JSON.stringify(result))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

But as you can see, it dint work. How do I approach this? A little help, please.

CodePudding user response:

const arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a, b) => b.length - a.length)
const res = arr.reduce((acc, el) => {acc.push([el, acc.length == 0 ? 1 : el.length == acc[acc.length-1][0].length ? acc[acc.length-1][1] : acc[acc.length-1][1] 1]); return acc}, [])
console.log(JSON.stringify(res))
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If you want to do it your way, you can do something like the following:

let rank = 1
const arr = ['java','python','javascript','C','Swift','Dart'];
arr.sort((a,b)=>b.length-a.length);
const result = [[arr[0], 1]]
for(let i=1;i<arr.length;i  ){
        if (arr[i].length<arr[i-1].length){
          rank} 
       result.push([arr[i],rank])
}
console.log(JSON.stringify(result))

CodePudding user response:

You could make use of the fact that object properties are iterated in order of index value:

const array = ['java','python','javascript','C','Swift','Dart'];

const buckets = Object.fromEntries(array.map(a => [a.length, []]));
for (let word of array) buckets[word.length].push(word);
const result = Object.values(buckets)
                     .reverse()
                     .map((bucket, rank) => bucket.map(word => [rank 1, word]))
                     .flat();

console.log(result);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related