Related
Similar to How to sort strings in JavaScript but I want to avoid sorting first, I just want the "largest" value of a string. For example
f(['Aa', 'B', 'C', 'Acd', 'Ace']) == 'C'
I am thinking it's something with .reduce like
const f = (a) => a.reduce(someFunctionGoesHere)
Where some function has an undefined check
UPDATE: Got it working but looks fugly. I wonder if I can reduce that function
const someFunctionGoesHere = (prev, current) => {
if (!prev) {
return current;
}
else if (prev.localeCompare(current) < 0) {
return current;
} else {
return prev;
}
};
const f = (a) => a.reduce(someFunctionGoesHere)
console.log(f(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));
UPDATE: this works, one line, but looks quite ugly. I guess this is the best that can be done with Javascript itself.
const maxString = (a) => a.reduce((prev, current) => (!prev || prev.localeCompare(current) < 0) ? current : prev)
console.log(maxString(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));
Indeed, reduce() will get you there:
const f = (array) => array.reduce((a, v) => v.localeCompare(a) > 0 ? v : a, '');
console.log(f(['Aa', 'B', 'C', 'Acd', 'Ace','CC']));
Say you have the following array:
const ab = ['a', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'a'];
How would you change this array so that all the "b" items get grouped together, until you hit another "a".
So the result of the above array would look like:
['a', 'a', 'bbb', 'a', 'bb', 'a'];
I'm trying to solve a problem with wrapping span tags around words that match a patter in a React app, but this is essentially my problem.
I've been working at it for ages but can't come up with anything I'm happy with.
Any ideas?
Cheers.
Count repeating occurences, then build the result based on that:
const result = [];
let curr = array[0], count = 1;
for(const el of array.slice(1).concat(undefined)) {
if(el !== curr || el !== "b") {
result.push(curr.repeat(count));
curr = el, count = 1;
} else count++;
}
Assuming the elements will always be single letters, you can merge the elements, then match on either bs or non-bs:
ab.join('').match(/(b+|.)/g)
const ab = ['a', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'a'];
let output = ab.join('').match(/(b+|.)/g);
console.log(output);
Using Array#reduce you could do something like this.
I'm assuming the first two characters in your solution were a typo.
const data = ['a', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'a'];
const res = data
.reduce((a,c)=>{
const lastIndex = a.length - 1;
if(a[lastIndex] && a[lastIndex].includes('b') && c === 'b') a[lastIndex] += c;
else a.push(c);
return a;
}, []);
console.log(res);
I don't know how to give an explanation for this but using reduce you can do it like this:
const ab = ['a', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'a'];
function merge(arr) {
return arr.reduce((acc,cur, index) => {
if(arr[index - 1] === 'b' && cur !== 'a') {
acc[acc.length - 1] = acc[acc.length - 1] + cur;
return acc;
}
acc.push(cur);
return acc;
},[]);
}
console.log(merge(ab))
Here's what you're after:
var ab = ['a', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'a'];
var index = 0;
var groupedArray = [];
var firstOccurence = true;
var groupedString = "";
var grouping = false;
for (var a = 0; a < ab.length; a++) {
if (ab[a] == "a") {
if (grouping) {
grouping = false;
firstOccurence = true;
groupedArray.push(groupedString);
}
groupedArray.push(ab[a]);
} else {
if (firstOccurence) {
groupedString = "";
firstOccurence = false;
}
groupedString += ab[a];
grouping = true;
}
}
console.log(groupedArray);
If you just want to merge b then you could use reduce like this:
If the current item and the previous item are b, then append it to the last accumulator item. Else, push it to the accumulator
const ab = ['a', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'a']
const output = ab.reduce((acc, c, i, arr) => {
arr[i-1] === "b" && c === "b"
? acc[acc.length - 1] += c
: acc.push(c)
return acc;
},[])
console.log(output)
You can just map through the ab array and if the current element is a, push it to a new array but if the current element is b, check if the previous element is b or not, and if it is, merge the current element to the previous element else just push the b to the new array.
const ab = ['a', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'a'];
let arr = [];
ab.map((e,i) => {
if(i > 0) { // check if element is the first one or not
if(e == "b") {
if(ab[i - 1].indexOf('b') > -1) { // check if prev element is "b" or not
arr[arr.length-1] += e; // merge if prev element is "b"
} else {
arr.push(e);
}
} else {
arr.push(e);
}
} else {
arr.push(e);
}
});
console.log(arr);
N.B. The reduce() method approach and the regex approach shown in the other answers are cleaner and more concise as compared to the map() method approach shown above though.
you can stringify your array then split it with a match of b or more or any other character
const ab = ['a', 'a', 'b', 'b', 'b', 'a', 'b', 'b', 'a'];
const res = ab.join("").match(/(b{1,}|.)/g);
console.log(res)
Input:
['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
Desired output:
['aaa', 'bb', 'ccc', 'd', 'ee']
Is this possible?
Edit: I forgot to mention that my previous attempt (for another example) failed, and I cannot figure out why:
let newArr = []
let last
let current
for (var i = 0; i < arr.length; i ++) {
last = last || isCurrencyArr[i]
current = isCurrencyArr[i]
let str = ''
if (last === current) {
str += arr[i]
} else {
newArr.push(str)
str = ''
}
last = isCurrencyArr[i]
}
Your example has a few hiccups. It redeclares str inside each iteration, therefore it only ever pushes empty strings. Also, it pushes the previous string when it comes across a new item, but it doesn't account for scenarios where the last items are the same, as in your example with the letter e.
If you're joining alike elements together, regardless of position...
Instead, you could use reduce() and spread syntax for object literals to build an object that keeps track of the occurrences of each item.
The object after reduce() looks like this:
{ a: "aaa", b: "bb", c: "ccc", d: "d", e: "ee" }
Once that object is built, all we have to do is create an array from the values using Object.values().
const arr = ['a', 'b', 'a', 'c', 'b', 'a', 'e', 'd', 'c', 'e', 'c'];
let items = arr.reduce((acc,i) => acc[i] ? {...acc, [i]: acc[i]+i } : {...acc, [i]: i }, {});
let result = Object.values(items);
console.log(result);
If you only want to join adjacent alike elements...
The example below uses a slightly similar approach to the above, however this reduce() outputs a string. The logic is similar to your own example: if the previous item is the same, add it to a string. If it is not, separate it and keep going.
The result is something like this: aaa|bb|ccc|d|ee. To turn that into an array, we just need to do split("|").
const arr = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e'];
let result = arr
.reduce((acc,i,idx,a) => (a[idx-1] === i || idx===0) ? acc+i : acc+"|"+i, "")
.split("|");
console.log(result);
This can be a solution to join adjacent elements:
const arr = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e'];
const resp = arr.reduce((a, e) => {
if(a.length === 0) return a.concat(e);
if(e === a[a.length - 1].split('').reverse()[0]) {
a[a.length - 1] = a[a.length - 1].split('').concat(e).join('');
return a;
}
return a.concat(e);
}, [])
console.log(resp);
Something like this should work:
function simplify(arr) {
let current = arr[0];
let final_arr = [];
let accumulated = current;
for (let i = 1; i < arr.length; i += 1) {
if (current === arr[i]) {
accumulated += arr[i];
} else {
final_arr.push(accumulated)
current = arr[i];
accumulated = current;
}
}
final_arr.push(accumulated);
return final_arr;
}
Using Array#reduce, spread syntax, and Map.
const data = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e'];
const res = [...data.reduce((a,c)=>{
return a.set(c, (a.get(c)||"") + c);
}, new Map()).values()];
console.log(res);
Algo for strictly adjacent elements.
const data = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e'];
const res = [];
for(let i = 0; i < data.length; i++){
const c = data[i];
let str = c;
for(let j = i + 1; j < data.length && c === data[j]; j++,i++){
str += c;
}
res.push(str);
}
console.log(res);
This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 4 years ago.
let array = ['a', 'a', 'a', 'b', 'b', 'c'];
i want to group double values from array, to get result like this:
result:
['3a, 2b, c']
(or something similar)
Any idea?
You can use .reduce() and .map() methods:
let array = ['a', 'a', 'a', 'b', 'b', 'c'];
let result = Object.entries(
array.reduce((r, c) => (r[c] = (r[c] || 0) + 1, r) , {})
).map(([k, v]) => v == 1 ? k : v + k);
console.log(result);
You can also use Map if you need items in specific order:
let array = ['a', 'a', 'a', 'b', 'b', 'c'];
let result = (((arr, map) => {
arr.forEach(s => map.set(s, (map.get(s) || 0) + 1));
return [...map.entries()].map(([k, v]) => v == 1 ? k : v + k);
})(array, new Map()));
console.log(result);
I would recommend using a dictionary to track the duplicate values in the array.
var dictionary = {};
for(var i = 0;i < array.length;i++){
var value = array[i];
if(dictionary[value] === undefined){
dictionary[value] = 0;
}
dictionary[value] = dictionary[value] + 1;
}
console.log(dictionary)
function count() {
array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current_elements = null;
var count= 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current_elements) {
if (cnt > 0) {
console.log(current_elements+count);
}
current_elements= array_elements[i];
count= 1;
} else {
count++;
}
}
if (cnt > 0) {
console.log(current_elements+count);
}
}
A single loop approach for simple run-length encoding (RLE) function.
let array = ['a', 'a', 'a', 'b', 'b', 'c'],
result = array.reduce(
(r, c, i, a) => r.concat(c === a[i - 1]
? ((+r.pop().slice(0, -1) || 1) + 1) + c
: c),
[]
);
console.log(result);
You can use Array.reduce() to produce an object with key-value (array value and count) pairs, then Array.map() to produce an array using Object.keys().
let array = ['a', 'a', 'a', 'b', 'b', 'c'];
let countObj = array.reduce((acc, val) => (acc[val] = acc[val] ? acc[val] + 1 : 1, acc), {});
console.log(countObj);
let countArr = Object.keys(countObj).map(key => '' + countObj[key] + key);
console.log(countArr);
For "something similar" why not just have an object that maps letter to occurrence. You can then simply use dot notation to get the property value assigned to each key.
Here I've used reduce.
const arr = ['a', 'a', 'a', 'b', 'b', 'c'];
// `reduce` over the arr
const obj = arr.reduce((acc, c) => {
// If the object (acc) we passed in doesn't have
// a key assigned to the letter in the current
// iteration (c) add it, set it to 0, then
// add one, otherwise, if there is a key, add one
acc[c] = (acc[c] || 0) + 1;
// Return the object for the next iteration
return acc;
// Pass in an initial object
}, {});
console.log(obj);
// Grab the value of `a` property
console.log(obj.a);
I have an Array with duplicate values.
I want to create a Set to get the distinct values of that array and remove or create a new Array that will have the same data MINUS the elements required to create the Set.
This is not just a matter of remove the duplicates, but remove a SINGLE entry of a each distinct value in the original array
Something like that works, but I wonder if there is a more direct approach:
let originalValues = [
'a',
'a',
'a',
'b',
'b',
'c',
'c',
'd'
];
let distinct = new Set(originalValues);
/*
distinct -> { 'a', 'b', 'c', 'd' }
*/
// Perhaps originalValues.extract(distinct) ??
for (let val of distinct.values()) {
const index = originalValues.indexOf(val);
originalValues.splice(index, 1);
}
/*
originalValues -> [
'a',
'a',
'b',
'c'
];
*/
Use Array#filter in combination with the Set:
const originalValues = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd'];
const remainingValues = originalValues.filter(function(val) {
if (this.has(val)) { // if the Set has the value
this.delete(val); // remove it from the Set
return false; // filter it out
}
return true;
}, new Set(originalValues));
console.log(remainingValues);
You could use closure over a Set and check for existence.
let originalValues = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd'],
result = originalValues.filter((s => a => s.has(a) || !s.add(a))(new Set));
console.log(result);
You should not use indexOf inside a loop, because it has linear cost, and the total cost becomes quadratic. What I would do is use a map to count the occurrences of each item in your array, and then convert back to an array subtracting one occurrence.
let originalValues = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd'];
let freq = new Map(); // frequency table
for (let item of originalValues)
if (freq.has(item)) freq.set(item, freq.get(item)+1);
else freq.set(item, 1);
var arr = [];
for (let [item,count] of freq)
for (let i=1; i<count; ++i)
arr.push(item);
console.log(arr);
If all items are strings you can use a plain object instead of a map.
You can create a simple Array.prototype.reduce loop with a hash table to count the number of occurrences and populate the result only if it occurs more than once.
See demo below:
var originalValues=['a','a','a','a','b','b','b','c','c','d'];
var result = originalValues.reduce(function(hash) {
return function(p,c) {
hash[c] = (hash[c] || 0) + 1;
if(hash[c] > 1)
p.push(c);
return p;
};
}(Object.create(null)), []);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
Instead of using Set for this you could just use reduce() and create new array with unique values and also update original array with splice().
let oV = ["a", "a", "a", "a", "b", "b", "c", "c", "d"]
var o = {}
var distinct = oV.reduce(function(r, e) {
if (!o[e]) o[e] = 1 && r.push(e) && oV.splice(oV.indexOf(e), 1)
return r;
}, [])
console.log(distinct)
console.log(oV)
As an alternate approach, you can use following algorithm that will remove only 1st entry of a duplicate element. If not duplicate, it will not remove anything.
const originalValues = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd'];
var r = originalValues.reduce(function(p, c, i, a) {
var lIndex = a.lastIndexOf(c);
var index = a.indexOf(c)
if (lIndex === index || index !== i)
p.push(c);
return p
}, [])
console.log(r)
If duplicates are not case, then you can directly remove first iteration directly
const originalValues = ['a', 'a', 'a', 'b', 'b', 'c', 'c', 'd'];
var r = originalValues.filter(function(el, i) {
return originalValues.indexOf(el) !== i
})
console.log(r)