Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
kth largest element(string) in an array based on length

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))

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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))

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))
about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!