-1

I have an array with values and I am wondering what would be the best approach to reduce it if value repeat for example 3 or 4 times?

I know how to remove duplicates, but what if I want the value to be repeated two times?

Let's have for example this:

let arr = [1,1,1,3,3,2,4,4,7,7,7,7]
let n = 2 //so I want numbers to repeat maximum two times

Result would be:

[1,1,3,3,2,4,4,7,7]
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available static and instance methods of [`Object`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods). – Sebastian Simon Aug 05 '21 at 10:53

1 Answers1

0

Look at this, might be helpful:

const reducer = (arr, n) => Object
   .entries(arr.reduce((all, x) => (all[x] ? all[x]++ : all[x] = 1, all), {}))
   .reduce((arr, x) => arr.concat(Array(x[1] > n ? n : x[1]).fill(x[0])), []);

let arr = [1,1,1,3,3,2,4,4,7,7,7,7]
let n = 2
reducer(arr, n) // Array(9) [ "1", "1", "2", "3", "3", "4", "4", "7", "7" ]
Farhad Rad
  • 563
  • 2
  • 15