How do you merge certain items in a JavaScript array? - javascript

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)

Related

Find an element with maximum occurrence in an Array - Javascript [duplicate]

This question already has answers here:
Get the element with the highest occurrence in an array
(42 answers)
Closed 4 months ago.
Input :
['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']
Expected output :
'B'
The output should be the element with higher occurrence. If there are two or more elements which shares the same number of occurrence, then the element which reaches the maximum count earlier in the array should be the expected output. In the above case, 'B' and 'A' has count of 3. Since 'B' reaches the max count earlier than 'A', 'B' should be the output.
I have already found the solution for this.
My Solution
let input = ['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']
const findWinner = (arr) => {
const reduced = arr.reduce((acc, value) => ({ ...acc,
[value]: (acc[value] || 0) + 1
}), {})
let pickLargest = Object.entries(reduced)
const winner = pickLargest.reduce((acc, [key, value]) => {
if (value > acc.maxValue) {
acc.maxValue = value
acc.winner = key
} else if (value == acc.maxValue) {
if (arr.lastIndexOf(key) > arr.lastIndexOf(acc.winner)) {
acc.winner = acc.winner
} else {
acc.winner = key
}
}
return acc
}, {
maxValue: 0,
winner: ''
})
return winner.winner
}
console.log(findWinner(input));
Is there any other elegant way to achieve the same result?
You could take an object for keeping track of the counts and adjust max, if necessary.
const
findWinner = array => {
const counts = {};
let max;
for (const value of array) {
counts[value] = (counts[value] || 0) + 1;
if (counts[value] <= counts[max]) continue;
max = value;
}
return max;
};
console.log(findWinner(['A', 'B', 'C', 'A', 'D', 'B', 'B', 'A', 'D']));
This should work:
const findWinner = ary => {
const occurrences = Object.fromEntries(ary.map(e => [e, 0]));
for(let el of ary){
occurrences[el]++
}
let sorted = Object.entries(occurrences).sort((a, b) => a[1] > b[1]);
return sorted[0][0];
}

JavaScript Join Identical Adjacent Elements in an Array

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);

How do I return the similar values between 2 arrays, and in the order of the second?

I have 2 arrays. I am trying to return the similar values between the 2 but in the order of the second. For example, take a look at the two arrays:
array1 = ['a', 'b', 'c']
array2 = ['b', 'c', 'a', 'd']
What I would like to return is this:
sim = ['b', 'c', 'a']
Here is a link to what I am trying to accomplish. Currently the script is faulty and not catching the corner case.
You could use a Set for array1 use Array#filter array2 by checking the set.
var array1 = ['a', 'b', 'c'],
array2 = ['b', 'c', 'a', 'd'],
theSet = new Set(array1),
result = array2.filter(v => theSet.has(v));
console.log(result);
Some annotations to your code:
function arr_sim (a1, a2) {
var //a = {}, // take an object as hash table, better
a = Object.create(null), // a really empty object without prototypes
sim = [],
i; // use single declaration at top
for (i = 0; i < a1.length; i++) { // iterate all item of array 1
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
sim.push(a2[i]); // just push the value
}
}
return sim;
}
console.log(arr_sim(['a', 'b', 'c'], ['b', 'c', 'a', 'd']));
You can iterate array2 with a filter, and check if the value is contained in array1:
let array1 = ['a', 'b', 'c'];
let array2 = ['b', 'c', 'a', 'd'];
let sim = array2.filter((entry) => {
return array1.includes(entry);
});
console.log(sim);
I think this is what you are looking for?
function arr_sim (a1, a2) {
a1 = Array.isArray(a1)?a1:typeof a1 == "string"?a1.split(""):false;
a2 = Array.isArray(a2)?a1:typeof a2 == "string"?a2.split(""):false;
if(!a1 || !a2){
alert("Not valid values");
return;
}
var filterArray = a1.filter(function(val){
return a2.indexOf(val) !== -1;
})
return filterArray;
}
console.log(arr_sim(['a', 'b'], ['b', 'a', 'c', 'd']));
console.log(arr_sim("abcd", "abcde"));
console.log(arr_sim("cxz", "zcx"));
Try this
const arr_sim = (a1, a2) => a2.filter(a => a1.includes(a))
console.log(arr_sim(['a', 'b', 'c'], ['b', 'c', 'a', 'd']));
try this example here similar-values betwe
en two arrays
var a1 = ['a' ,'b'];
var a2 = ['a' ,'b' ,'c'];
var result = arr_sim(a1,a2);// call method arr_sim
console.log(result);
function arr_sim (a1, a2) {
var similar = [];
for( var i = 0 ; i <a1.length ; i++ ){ // loop a1 array
for( var j = 0 ; j <a2.length ; j++ ){ // loop a2 array
if( a1[i] == a2[j] ){ // check if is similar
similar.push(a1[i]); // add to similar array
break; // break second loop find that is similar
} // end if
} // end second lopp
} // end first loop
return similar; // return result
} // end function

How to create a Set from Array and remove original items in JavaScript

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)

Minimize an array with repeaters values Javascript

I'm trying to do something interesting in JavaScript, but I can't. This is my input:
var Input = ['a','a','a','b','b','b','b','c','c','c','a','a','c','d','d','d'];
So my output is that only get differents values and go in a new vector.
var Output = SomeFunction(Input);
This is what I want:
Output = ['a','b','c','a','c','d'];
Y tried with this, but don't work aswell:
function SomeFunction(input){
var out= [];
for (var i = 0; i < input.length - 1; i++) {
if(input[i] == input[i+1]){
out.push(input[i]);
}
}
return out;
}
You can use filter()
var input = ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'a', 'a', 'c', 'd', 'd', 'd'];
input = input.filter(function(v, i, arr) {
return arr[i - 1] !== v;
//compare with the previous value
})
document.write(JSON.stringify(input));
You can use backreferencing regex
Convert the array to string by using join, so that regex can be used on it
Use backreferencing regex to remove the consecutive elements with replace()
Convert back the string to array using split
(\w)\1* Explanation
var input = ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'a', 'a', 'c', 'd', 'd', 'd'];
var str = input.join('');
input = str.replace(/(\w)\1*/g, '$1').split('');
console.log(input);
document.write('<pre>' + JSON.stringify(input, 0, 2) + '</pre>');
You can do a filter like
var Input = ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'a', 'a', 'c', 'd', 'd', 'd', 'e'];
var Output = SomeFunction(Input);
function SomeFunction(input) {
var out = input.filter(function(value, i) {
return value !== input[i + 1]
});
return out;
}
output.innerHTML = JSON.stringify(Output)
<pre id="output"><pre>
Try like this
var out= [];
var i = 0;
for (i = 0; i < input.length - 1; i++) {
if(input[i] != input[i+1]){
out.push(input[i]);
}
}
if (out[out.length-1] !== input[i])
out.push(input[i]);
How about this:
var Input = ['a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'a', 'a', 'c', 'd', 'd', 'd'];
function SomeFunction(input) {
var out = [];
var initStr = input[0];
console.log(initStr)
for (var i = 1; i < input.length; i++) {
if (input[i] === initStr) {
} else {
out.push(input[i - 1]);
initStr = input[i];
}
}
out.push(input[i - 1]);
console.log(out);
}
SomeFunction(Input)
function SomeFunction(input) {
var out= [];
out.push(input[i]);
for (var i = 0; i < input.length - 1; i++) {
if(input[i] !== out[out.length-1]){
out.push(input[i]);
}
}
return out;
}
Worked for me:
function SomeFunction(input){
var out= [];
for (var i = 0; i < input.length; i++) {
if(input[i] !== input[i+1]){
out.push(input[i]);
}
}
return out;
}
Be careful with the name of the varible "input". It's not "Input", it's "input".
Example using array filters.
Pretty simple as long as the array is not too large and could rather easily be extended to compare some property in an array of objects. With a larger array it might be faster though to do a for loop instead as in some of the other answers.
var Input = ['a', 'b', 'c','a', 'b', 'a', 'b', 'c','c']
var Output = Input.filter(function(value,index) { return Input[index - 1] != value; });
var Input = ['a','a','a','b','b','b','b','c','c','c','a','a','c','d','d','d'];
var Output = SomeFunction(Input);
function SomeFunction(input){
var out= [];
for (var i = 1; i < input.length; i++) {
if(input[i] != input[i-1]){
out.push(input[i-1]);
}
}
out.push(input[input.length - 1]);
return out;
}
alert(Output);

Categories

Resources