for an array of
['one', 'one', 'two', 'two', 'three', 'one']
use the pattern ['one', 'two', 'three'] to turn that into
['one', 'two', 'three', 'one', 'two', 'one']
my thought is
const sortArray = oldArray => {
let newArr = [];
while (newArr < oldArray.length) {
// loop through array
for (let i = 0; i < arr.length; i++) {
// loop through pattern
for (let j = 0; j < pattern.length; j++) {
// match
if (arr[i] === pattern[j]) {
// add item to new array
newArr.push(arr[i]);
// remove item from old array
arr.shift();
} else {
// push item to end of array
arr.push(arr[i]);
// remove item from array
arr.shift()
}
}
}
}
return newArray;
}
I can do this using a map, it's what I'm used to for solving stuff like this but when it comes to iterating through just an array with a pattern I get super confused. any suggestions?
with a map, this is how I'd do it
let a = ['one', 'one', 'two', 'two', 'three', 'one'];
const printValues = (arr, pattern) => {
let map = {};
let a = [];
arr.forEach((v) => {
if (!map[v]) map[v] = 1;
else map[v]++;
})
while (a.length !== arr.length) {
pattern.forEach((v) => {
if (map[v] > 0) {
a.push(v);
map[v]--;
}
})
}
console.log(a);
}
console.log(printValues(a, ['one', 'two', 'three']))