I currently have a problems counting the distance between the max value and other values in array. Basically I want to make a new array where the values will be the distances from the max value. What I mean by this:
Example
I have an array of objects:
var array = [
{
id: 1,
value: 20,
},
{
id: 2,
value: 10,
},
{
id: 3,
value: 10,
},
{
id: 4,
value: 3,
},
{
id: 5,
value: 2,
},
];
}]
I want the result of this new algorithm that I am trying to make to be like this:
Result
var newArray = [0, 1, 1, 2, 3]
Reason for this are the distance between the max value and other values that we have. The values that are same needs to have the same distance. Max value is 20 so it needs to have 0 as a result, 10 is second value and it is 1 distance away from max value and so on.
What should I do to start working on this?
CodePudding user response:
In the case your array is already sorted:
var array = [
{
id: 1,
value: 20,
},
{
id: 2,
value: 10,
},
{
id: 3,
value: 10,
},
{
id: 4,
value: 3,
},
{
id: 5,
value: 2,
},
];
const order = new Set(array.map(el => el.value))
const res = array.map(el => [...order].indexOf(el.value))
console.log(res)
in case you need to sort the array before:
var array = [
{
id: 1,
value: 10,
},
{
id: 2,
value: 10,
},
{
id: 3,
value: 20,
},
{
id: 4,
value: 3,
},
{
id: 5,
value: 2,
},
];
const sortedArray = array.sort((a,b) => a.value >= b.value ? -1 : 1)
const order = new Set(sortedArray.map(el => el.value))
const res = sortedArray.map(el => [...order].indexOf(el.value))
console.log(res)
CodePudding user response:
- Create an array with just the unique values, sorted from high to low
- Map over the
array
and get the index of that value in the array from step-1
var array = [{id: 1, value: 20, }, {id: 2, value: 10, }, {id: 3, value: 10, }, {id: 4, value: 3, }, {id: 5, value: 2, }, ];
var vals = array.map(a => a.value)
.filter((v, i, s) => s.indexOf(v) === i)
.sort((a, b) => b - a);
var res = array.map(v => vals.indexOf(v.value));
console.log(res); // [0, 1, 1, 2, 3]
CodePudding user response:
This one doesn't care whether the array is originally sorted; as it starts by sorting a shallow copy.
const positions = (xs, ys = [...xs] .sort ((a, b) => b .value - a .value)) =>
xs .map (x => ys .findIndex (y => x .value == y.value))
const array1 = [{id: 1, value: 20}, {id: 2, value: 10}, {id: 3, value: 10}, {id: 4, value: 3}, {id: 5, value: 2}]
const array2 = [{id: 1, value: 10}, {id: 2, value: 10}, {id: 3, value: 20}, {id: 4, value: 3}, {id: 5, value: 2}]
console .log (positions (array1))
console .log (positions (array2))
Then all we do is map our inputs to find the index of the first object in the sorted version that has the same value
.