Reputation: 403
I have the following array and I am looking to retrieve the index of the original (sorted) array where the element is changing and how often that individual element exists.
ab = [1,1,1,3,3,5,5,5,5,5,6,6]
The desired outcome should be like this:
ac = [0,3,5,10]
ad = [3,2,5,2]
Thank you very much for any suggestion.
Cheers.
Upvotes: 5
Views: 622
Reputation: 303
I think this works in R. YMMV
> ab = c(1,1,1,3,3,5,5,5,5,5,6,6)
> i1<-1:length(ab)
> i2<-c(2:length(ab),length(ab))
> i3<-ab[i1]!=ab[i2]
> ac<-c(0,i1[i3])
> ac
[1] 0 3 5 10
> ad<-c(ac[-1],length(ab))-ac
> ad
[1] 3 2 5 2
Upvotes: 0
Reputation: 22776
This code produces similar output to the one you posted:
var ab = [1,1,1,3,3,5,5,5,5,5,6,6];
var ac = Array.from(new Set(ab.map((e) => ab.indexOf(e))));
var ad = [];
for (var i = 0; i < ac.length - 1; i++) {
ad.push(ac[i + 1] - ac[i]);
}
ad.push(ab.length - ac[ac.length - 1]);
console.log(...ab);
console.log(...ac);
console.log(...ad);
Upvotes: 2
Reputation: 3456
so, using https://underscorejs.org/#groupBy you can group by value
_.groupBy([1,1,1,3,3,5,5,5,5,5,6,6]);
or
_.groupBy([1,1,1,3,3,5,5,5,5,5,6,6], function(num){ return num; })
you will get an object like
{1: [1,1,1], 3: [3,3], 5: [5,5,5,5,5], 6: [6,6]}
so if you take all https://underscorejs.org/#keys and iterate through, value under key is array, take size and append to new array, so you can make ad = [3,2,5,2]
again, iterate through keys and get https://underscorejs.org/#indexOf , you can construct ac = [0,3,5,10]
play around these methods, check examples, and you can do it yourself!
Upvotes: 1
Reputation: 550
Try this, should get you what you want
ab = [1,1,1,3,3,5,5,5,5,5,6,6];
var items = [];
var positions = [];
var count = [];
ab.map((item, index)=>{
//check if exist
let item_index = items.indexOf(item);
if(item_index == -1) {
items.push(item);
positions.push(index);
count.push(1);
} else {
let current_count = count[item_index];
count[item_index] = ++current_count;
}
});
console.log(positions);
console.log(count);
Upvotes: 1
Reputation: 386680
You could iterate the array and check the predecessor. If equal, increment the last count, otherwise add the index and a count of one.
var array = [1, 1, 1, 3, 3, 5, 5, 5, 5, 5, 6, 6],
{ indices, counts } = array.reduce((r, v, i, a) => {
if (a[i - 1] === v) {
r.counts[r.counts.length - 1]++;
} else {
r.indices.push(i);
r.counts.push(1);
}
return r;
}, { indices: [], counts: [] });
console.log(...indices);
console.log(...counts);
Upvotes: 5