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);
Related
This may be a duplicate question. But I didn't find any similar questions in this forum.
I'm trying to modify values in an array to different format.
arrayInput = ['A', 'B', 'C', 'D', 'E', 'F'];
arrayOutput= ['A;B', 'C;D', 'E;F'];
I got the solution with the following approach
let arrayInput = ['A', 'B', 'C', 'D', 'E', 'F']
arrayOutput = [arrayInput[0]+';'+ arrayInput[1], arrayInput[2]+';'+ arrayInput[3]];
if (arrayInput[4]) {
let val = arrayInput[4] + (arrayInput[5] ? ';'+arrayInput[5] : '');
arrayOutput.push(val);
}
console.log(arrayOutput);
But I am looking for a generic solution such that even if I have more items in array, it should generate the output in desired format.
['A', 'B', 'C', 'D', 'E', 'F', 'G'] ==> ['A;B', 'C;D', 'E;F', 'G']
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] ==> ['A;B', 'C;D', 'E;F', 'G;H']
Thanks for the support
You can use Array#reduce as in the following demo. Just in case there's an odd number of elements, I have included a test here ${arr[i+1] ? ";" + arr[i+1] : ""}; otherwise use ${arr[i+1]}, if you always have an even number of elements.
const arrayInput = ['A', 'B', 'C', 'D', 'E', 'F'],
arrayOutput = arrayInput.reduce(
(acc,cur,i,arr) =>
i % 2 === 0 ?
[...acc,`${cur}${arr[i+1] ? ";" + arr[i+1] : ""}`] :
acc,
[]
);
console.log( arrayOutput );
//OUTPUT: ['A;B', 'C;D', 'E;F'];
Use a for loop, and increment it by 2 every iteration:
const arrayInput = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
const res = [];
for (let i = 0; i < arrayInput.length; i += 2) {
const part1 = arrayInput[i];
const part2 = arrayInput[i + 1];
if (part1) {
res.push(part1 + (part2 ? (';' + part2) : ''));
}
}
console.log(res);
You can try something like this (implementation based on array reduce and join):
const arrayInput = ['A', 'B', 'C', 'D', 'E', 'F'];
let temp = [];
const output = arrayInput.reduce((accumulator, item) => {
if (temp.length < 2) {
temp.push(item);
} else {
accumulator.push(temp.join(';'));
temp = [];
}
return accumulator;
}, []);
console.log(output)
Using a foreach :
let arrayInput = ['A', 'B', 'C', 'D', 'E', 'F','G','H','I']
let newArray = [];
arrayInput.forEach((e,i) => {
if((i + 1)%2==0)
{
newArray[newArray.length -1] = `${newArray[newArray.length -1]};${e}`
}
else
{
newArray.push((i + 1) < newArray.length ? `${e};` : e)
}
});
console.log(newArray)
I've been looking for a while at this thread but all i could find there as results of comparaison between two arrays are which elements were added or removed.
What i need is to just guess which element has moved from an index to another.
Example: let's take the following array:
let array1 = ['A', 'B', 'C', 'D', 'E', 'F'];
The 'E' element will move from the 4th index to the 2nd index and we wil get :
let array2 = ['A', 'B', 'E', 'C', 'D', 'F'];
I need a function that returns which element has changed , its new index in the new array2 and its old index in the array1;
I've made such as algo in the past which roughly (from what i remember now) consists of looking for the first different element between both arrays then to check the sequence behind it to guess if the diff element found is itself the moved one or the one which took its place.
So before rewritting it , i wished i could find one ready to use ;)
The approach is as follows ...
iterate one of the arrays, preferably the current one.
for each current item/value get its index from the recent array ...
... and compare this item's/value's current index to its recent index.
in case both indices do not equal (including a recent index of -1 due to a removed value/item) create a state like object with data of the value and the indices and push it into the result array.
The implementation is based on Array.prototype.reduce where on would process the current item array and would pass the recent item array as part of a accumulator/collector as the reducer function's initial value.
function collectPositionChange({ recent, result }, value, currentIdx) {
const recentIdx = recent.indexOf(value);
if (recentIdx !== currentIdx) {
result.push({ value, currentIdx, recentIdx });
}
return { recent, result };
}
const recentItems = ['A', 'B', 'E', 'C', 'D', 'F'];
const currentItems = ['A', 'B', 'C', 'D', 'E', 'F'];
console.log(
currentItems
.reduce(collectPositionChange, { recent: recentItems, result: [] })
.result
);
console.log(
['A', 'C', 'D', 'B', 'E', 'F']
.reduce(collectPositionChange, { recent: ['A', 'B', 'C', 'D', 'E', 'F'], result: [] })
.result
);
console.log(
['A', 'B', 'C', 'D', 'E', 'F']
.reduce(collectPositionChange, { recent: ['A', 'C', 'D', 'B', 'E', 'F'], result: [] })
.result
);
.as-console-wrapper { min-height: 100%!important; top: 0; }
I am not sure what the full requirements are, but this will detect forward and backwards movement as well as character swaps. It will work on any order, but its prediction on what changed gets less accurate the more changes that occur in a row.
Here is a sample that uses a dictionary:
const array1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'];
const array2 = ['A', 'B', 'E', 'C', 'D', 'F', 'H', 'I', 'G', 'K' , 'J'];
let globalOffset = 0;
let currentSuspect = "";
var dict = new Object();
array1.forEach((char, index) => {
dict[char] = index;
});
array2.forEach((char, index) => {
dict[char] = dict[char] - index;
});
let offset = 0;
let prevValue = 0;
Object.entries(dict).forEach((entry, index) => {
const [key, value] = entry;
switch(true){
case offset === 0 && value < -1:
console.log(`The character ${key} had its index moved forward by ${Math.abs(value)}! \n New index: ${index + Math.abs(value)} - Old index: ${index}`);
break;
case offset < 0 && value > 1:
console.log(`The character ${key} had its index moved backwards by ${value}! \n New index: ${index + offset} - Old index: ${index}`);
break;
case prevValue === -1 && offset === -1 && value === 1:
console.log(`The characters ${key} and ${array2[index]} were swapped!`);
break;
}
prevValue = value;
offset += value;
});
let array1 = ['A', 'B', 'C', 'D', 'E', 'F'];
// test 1 : moving 'B' from index 1 to index 3
let array2 = ['A', 'C', 'D', 'B', 'E', 'F'];
// test 2: moving 'E' from 4 to 1
// let array2 = ['A', 'E', 'B', 'C', 'D', 'F'];
// test 3 : moving 'A' from 0 to 5
// let array2 = ['B', 'C', 'D', 'E', 'F', 'A'];
function getMovedElementInfos(array1, array2) {
let firstDiffElIndexInNewArray = array2.findIndex((el, elindx) => el !== array1[elindx]);
let firstDiffElInNewArray = array2[firstDiffElIndexInNewArray];
let nextElInNewArray = array2[firstDiffElIndexInNewArray + 1];
let firstDiffElIndexInOldArray = array1.findIndex(el => el === firstDiffElInNewArray);
let nextElInOldArray = array1[firstDiffElIndexInOldArray + 1];
let movedEl, movedElFrom, movedElTo;
if (nextElInNewArray === nextElInOldArray) {
movedEl = array1[firstDiffElIndexInNewArray];
movedElFrom = firstDiffElIndexInNewArray;
movedElTo = array2.findIndex(el => el === movedEl);
} else {
movedEl = firstDiffElInNewArray;
movedElFrom = firstDiffElIndexInOldArray;
movedElTo = firstDiffElIndexInNewArray;
}
return {
movedEl,
movedElFrom,
movedElTo
}
}
const {
movedEl,
movedElFrom,
movedElTo
} = getMovedElementInfos(array1, array2)
console.log('movedEl is: ', movedEl);
console.log('movedEl index in old array is: ', movedElFrom);
console.log('movedEl index in new array is: ', movedElTo);
console.log('array1[movedElFrom]: ', array1[movedElFrom]);
console.log('array2[movedElTo]: ', array2[movedElTo]);
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)
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)
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);