I have a array like this:
arr[1] = 100
arr[10] = 20
arr[20] = 10
When I iterate the array, I got:
arr[1]:100 arr[10]:20 arr[20]:10
Currently, the array is sorted by the index. How can I sort it by the value but KEEP the original index.
What I want is:
arr[20]:10 arr[10]:20 arr[1]:100
I checked other posts but didn't find a solution to this specific issue. I am not sure javascript supports this. Can I get some help?
Thanks!
When we speak of a sorted array in JavaScript, we mean that an iteration over the array by increasing index produces the values in sorted order.
Your requirements would actually require an array with pairs of ("index", value).
Here is how that works:
let arr = [];
arr[1] = 100;
arr[10] = 20;
arr[20] = 10;
let result = Object.entries(arr).sort((a, b) => a[1]-b[1])
.map(([k, v]) => [+k, v]); // optional conversion
console.log(result);
Related
Do anyone understand why console.log(posArr) is printing [1,2,3] and not [0,1,2]. Im trying to push to nOfPos all the index positions of my array :)
function combinations(x) {
let arr = x.toString().split('');
console.log(arr)
let nOfPos = [];
let posArr = arr.map(x => nOfPos.push(arr.indexOf(arr[x])));
let mult = posArr.reduce((acum, item) => acum * item);
console.log(posArr);
console.log(mult);
}
combinations(123)
The problem is due to two errors in your code. Firstly push() returns the new length of the array, so that's why the mapped output contains the incremental 1,2,3....
Secondly, you need to search for x within arr, so you only need to pass x to indexOf().
With those issues corrected the code works:
function combinations(x) {
let arr = x.toString().split('');
let posArr = arr.map(x => arr.indexOf(x));
let mult = posArr.reduce((acum, item) => acum * item);
console.log(posArr);
console.log(mult);
}
combinations(123)
That being said, the purpose of posArr is a little redundant; it will always be an array of incremental values, up to the length of the string -1.
In addition, mult is redundant too as it will always be 0, as you are multiplying by 0.
You could use a 'for in' loop to get the array indexes.
let posArr = [];
for (ix in arr) {
posArr.push(ix)
}
I make an API call and it gives back the following:
[
[1529539200,15.9099,16.15,15.888,16.0773,84805.7,1360522.8],
[1529625600,16.0768,17.38,15.865,17.0727,3537945.2,58937516],
[1529712000,17.0726,17.25,15.16,15.56,3363347.2,54172164],
[1529798400,15.55,16.0488,15.3123,15.6398,2103994.8,33027598],
[1529884800,15.6024,15.749,13.3419,14.4174,3863905.2,55238030],
[1529971200,14.4174,15.1532,13.76,14.8982,2266159.8,33036208],
...
]
There are basically about 1000 objects in total, and every object has 7 objects within it, each of them containing the values shown above. Right now I have set
var objects= response.data.result[86400]
which gives the result you see above, and now, I need to search through these objects until Javascript finds the object that has the value '1529884800' in object zero, so for example with the code above this would result in this number:
object[5][0]
I wrote the following ode but it doesn't work, results in an empty array as response.
var results = [];
var toSearch = 1529539200;
for (var i=0; i<objects.length; i++) {
for (key in objects[i][0]) {
if (objects[i][key].indexOf(toSearch) != -1) {
results.push(objects[i]);
}
console.log(results)
}
}
(in the above results just shows [])
I tried doing var toSerach ='1529539200' and without quotes but neither work, what is the issue here? Would appreciate any help, thanks
If you want the index of a given number, use .flatMap() and .indexOf()
First iterate through the outer array
array.flatMap((sub, idx) =>
Then on each sub-array find the index of the given number. .indexOf() will either return the index of the number if it exists or -1 if it doesn't. In the final return it will be the index number of the sub-array and then the index of the number within the sub-array if found. Otherwise an empty array is returned which results in nothing because .flatMap() flattens arrays by one level.
sub.indexOf(number) > -1 ? [idx, sub.indexOf(number)] : [])
const data = [[1529539200,15.9099,16.15,15.888,16.0773,84805.7,1360522.8],[1529625600,16.0768,17.38,15.865,17.0727,3537945.2,58937516],[1529712000,17.0726,17.25,15.16,15.56,3363347.2,54172164],[1529798400,15.55,16.0488,15.3123,15.6398,2103994.8,33027598],[1529884800,15.6024,15.749,13.3419,14.4174,3863905.2,55238030],[1529971200,14.4174,15.1532,13.76,14.8982,2266159.8,33036208]];
let A = 1529539200;
let B = 33036208;
let C = 15.16;
const findNumber = (array, number) =>
array.flatMap((sub, idx) =>
sub.indexOf(number) > -1 ? [idx, sub.indexOf(number)] : [])
console.log(findNumber(data, A));
console.log(findNumber(data, B));
console.log(findNumber(data, C));
I have an array with some duplicates value. I have removed all duplicates value and get his count(repeat).
Now I have to sort this data according to his count.
Example:
let duplicatis_data = ['a','a','b','b','b','c','c','c','c','d','e'];
Expected output
c->4
b->3
a->2
d->1
e->1
There is lots of example with removing the duplicates and return the count but they did not make filter according to count. So this is not a duplicate of those questions like below.
How to count duplicate value in an array in javascript
Calculate the frequency and then sort the array based on the frequency:
let duplicatis_data = ['a','a','b','b','b','c','c','c','c','d','e'];
const freq = duplicatis_data.reduce((c, v) => (c[v] = (c[v] || 0) + 1, c), {});
const result = Object.entries(freq).sort((x, y) => y[1] - x[1]);
console.log(JSON.stringify(result));
I am creating an object with dynamic keys as seen here:
const myObject = [
{PINO: 1764},
{FANH: 2737},
{WQTR: 1268},
{CICO: 1228}
];
I want to get the key and value with the lowest value, in this case it's {CICO: 1228}.
How I create this object is like so:
let basic = [];
_.map(values, value => {
let result = value[Object.keys(value)].reduce((c, v) => {
// sum up the amounts per key
c[Object.keys(value)] = (c[Object.keys(value)] || 0) + parseInt(v.amount);
return c;
}, {});
basic.push(result);
})
console.log(basic) => [{PINO: 1764}, {FANH: 2737}, {WQTR: 1268}, {CICO: 1228}]
How can I get the lowest number with it's key from the basic object? I tried using sort and taking the lowest number but the keys are created dynamically so I don't think I have anything I can sort against.
This is a pretty inconvenient way to store data since the keys are more-or-less useless and you need to look at the values of each object to do anything. But you can do it if you need to with something like:
const myObject = [
{PINO: 1764},
{FANH: 2737},
{WQTR: 1268},
{CICO: 1228}
];
let least = myObject.reduce((least, current) => Object.values(least)[0] < Object.values(current)[0] ? least : current)
console.log(least)
If it was a large list, you might benefit from converting the array to a different format so you don't need to keep creating the Object.values array.
Iterate the array with Array.reduce(), get the values of the objects via Object.values(), and take the one with the lower number:
const myObject = [
{PINO: 1764},
{FANH: 2737},
{WQTR: 1268},
{CICO: 1228}
];
const result = myObject.reduce((r, o) =>
Object.values(o)[0] < Object.values(r)[0] ? o : r
);
console.log(result);
I have a very simple question. Say I have an array
a = [10,40,30,20,60,50]
After sorting, it would be (assuming I use sort_a = a.sort())
sort_a = [60,50,40,30,20,10]
I want to create an array of indices from a which specify which location in the sorted array that element WILL BE after sorting. From the above example, the result would be
a_sortedindices = [6, 3, 4, 5, 1, 2]
..meaning 10 is in the 6th position when sorted, 40 is in the 3rd position... etc
Pair the values with their current indices
Sort the array of pairs based on the original values
Combine the pairs with their new indices
Sort the new array based on the original indices
Obtain the new indices from the sorted array
let values = [10,40,30,20,60,50];
let indices = values
.map((v, i) => ({ v, i }))
.sort((l, r) => r.v - l.v)
.map(({v, i}, i2) => ({ v, i, i2 }))
.sort((l, r) => l.i - r.i)
.map(p => p.i2);
console.log(indices);
This results in an array of 0-based indices because JavaScript uses 0-based indices. If you want 1-based indices like in your question, you can change p.i2 to p.i2 + 1 in the second to last line.
One of the ways, apart from many to achieve this:
1) Transform the array into another with old indices
2) Sort the array in descending order
3) Create an answer array since you now know the old and new indices.
let a = [10,40,30,20,60,50];
let transformed = a.map((v,i)=> {
return {num:v,old:i};
});
transformed.sort((a,b)=> {
return b.num - a.num;
});
let ans = [];
transformed.forEach((v,i) => {
ans[v.old] = i+1;
});
console.log(ans);
Not sure if this is a trick question or if you're trying to find the most minimal method for achieving this, but you basically already have it. This is what I came up with:
var a = [10,40,30,20,60,50];
var sort_a = a.slice(0).sort((a1,a2) => a2 - a1);
var a_sortedindices = a.map( a1 => sort_a.indexOf(a1) + 1 );
console.log(a_sortedindices);
Walking through it, I'll explain each part.
First, off you have to sort it. Looks like you need reverse sorting, so we'll add an arrow function describing a reverse sort, but before we do that, we'll also clone the array, otherwise we'll lose the original indexes of the values. .slice(0) is a nice way to return a clone of an array
var sort_a = a.slice(0).sort((a1,a2) => a2 - a1);
Then we'll map each value of the origin array. .map() is nice and easy to quickly manipulate each element in an array. We use .indexOf() to figure out where it was at in the original array. We add one to that value because you're not using zero-based indexing.
var a_sortedindices = a.map( a1 => sort_a.indexOf(a1) + 1 );
And voila. You have the sorted indexes.
A naive way of doing this job could be;
var arr = [10,40,30,20,60,50],
idx = arr.map(function(n){return this.indexOf(n)+1;}, arr.slice().sort((a,b) => b-a));
console.log(idx);
where the this argument for the .map() function callback is arr.slice().sort((a,b) => b-a)
// the array to be sorted
var list = [10,20,30,40];
// temporary array holds objects with position and sort-value
var mapped = list.map(function(el, i) {
return { index: i, value: el };
})
// sorting the mapped array
mapped.sort(function(a, b) {
return b.value - a.value;
});
// you can then remap the sorted mapped array to hold just the indices
P.S.: For future reference MDN is your friend