Home > Software design >  removing duplicate elements in an array and also the elements which is repeated most in the array sh
removing duplicate elements in an array and also the elements which is repeated most in the array sh

Time:08-07

const source = [2, 9, 9, 1, 6];

const ans = source.filter((item, index, arr)=> arr.indexOf(item) === index);

console.log(ans);

here i'm able to remove the duplicate elements but how to make 9 which is repeated highest to come first in the new array?? any help would be appreciated

ans should be [9, 2, 1, 6]

CodePudding user response:

If using more space is okay, you can use a hash map for counting elements and then convert it to an array.

Something like this.

let arr =  [2, 9, 9, 1, 6];
// count elements
const map = arr.reduce((acc, e) => acc.set(e, (acc.get(e) || 0)   1), new Map());

// sort by values and convert back to array
const res = [...map.entries()].sort((a, b) => b[0] - a[0]).map((a) => {
    return a[0]
});


console.log(res)

CodePudding user response:

Try This

function removeAndSort(arr) {
    var order = {};
    for (var i = 0; i < arr.length; i  ) {
        var value = arr[i];
        if (value in order) {
            order[value]  ;
        } else {
            order[value] = 1;
        }
    }
    var result = [];
    for (value in order) {
        result.push(value);
    }
    function sort(a, b) {
        return order[b] - order[a];
    }
    return result.sort(sort);
}

console.log(removeAndSort([2, 9, 9, 1, 6]));

It's Absolutely Working, Check It

CodePudding user response:

Instead of removing the duplicates with the code you have you need to find a way to create a frequency map to save the duplicates information. In this example I create a map using an object like this...

const freq = { 9: [9, 2], 1: [1, 1] ... };

which uses the current iterated element as a key in an object, and the value is the element along with its duplicate value. You can grab those arrays using Object.values, sort them by that duplicate value, and then map over that sorted nested array to produce the result.

Note, however, due to the sorting process this results in [9, 1, 2, 6].

const source = [2, 9, 9, 1, 6];

// `reduce` over the array creating a key/value pair where
// the value is an array - the first element is the element value,
// and the second value is its duplicate value
const nested = source.reduce((acc, c) => {

  // If the object property as defined by the element
  // value doesn't exist assign an array to it initialising
  // the duplicate value to zero
  acc[c] ??= [c, 0];

  // Increment the duplicate value
    acc[c][1];

  // Return the object for the next iteration
  return acc;

}, {});

// We take the `Object.values` of the object (a series of
// nested arrays and sort them by their duplicate value,
// finally `mapping` over the sorted arrays and extracting
// the first element of each
const out = Object.values(nested).sort((a, b) => {
  return b[1] - a[1];
}).map(arr => arr[0]);

console.log(out);

Additional documentation

CodePudding user response:

function sortAndFilter(source) {
    let duplicates = {};
    //count the duplications
    source.filter((item, index, arr) => {
        if(arr.indexOf(item) != index) 
            return duplicates[item] = (duplicates[item] || 0)   1;
        duplicates[item] = 0;
    })
   //sort the numbers based on the amount of duplications
    return Object.keys(duplicates).map(a => parseInt(a)).sort((a, b) => duplicates[b] - duplicates[a]);
}

Output: [ 9, 6, 2, 1 ]

This could do the job

CodePudding user response:

this is best answer for your question

const source = [2, 9, 9, 1, 6];

function duplicate(array) {
  let duplicates = array.filter((item, index) => array.indexOf(item) !== index);
  return duplicates.concat(array.filter((item) => !duplicates.includes(item)));
}

console.log(duplicate(source));

CodePudding user response:

This should work for all cases where array should be sorted by most number of reoccurrences.

const source = [2,1,9,9,6];
const indexes = [];

var ans = source.filter((item,index,arr)=>{
    if(arr.indexOf(item) === index){
        indexes.push({item:item,count:1})
        
        return true;
    }
    else if(arr.indexOf(item) !== index){
        
        indexes[indexes.findIndex(object=> object.item === item)].count  
        return false;
    }
    return false;

})

ans =(indexes.sort((a,b)=>{return b.count - a.count}).map(obj =>obj.item))

console.log(ans)

CodePudding user response:

Just add a sort:

 `function myFunction()  
{
const source = [2, 9, 9, 1, 6];

const ans = source.filter((item, index, arr)=> arr.indexOf(item) === 
index);
ans.sort((a, b) => b-a);

console.log(ans);

}

`

6:39:13 AM  Info    [ 9, 6, 2, 1 ]
  • Related