-
-
Save entrptaher/3cb24d85d20fe15e91028c940264897d to your computer and use it in GitHub Desktop.
Array splice implementation to convert an existing array to target array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
/** | |
* Fill gaps of an array | |
* @param {Object} sourceArray - The source array to compare to | |
* @param {Object} targetArray - The target array to fill the gap | |
* @param {string} Filler - The element to be used to fill the gap | |
*/ | |
let similarFill = ((sourceArray, targetArray, filler) => { | |
let pos = 0; | |
for (let i = 0; i < targetArray.length; i++) { | |
// if position is greater or equal of the source array length, then set position as 0 | |
if (pos >= sourceArray.length) { | |
pos = 0; | |
} | |
// if target element is not same as source element, then insert the filler element at that point | |
if (targetArray[i] != sourceArray[pos]) { | |
targetArray.splice(i, 0, filler); | |
} | |
// increase position along with the loop | |
pos += 1; | |
} | |
return targetArray; | |
}) | |
// Example Usage | |
let sourceElem = [1, 2, 3, 4, 5, 6]; | |
let targetElem = [ | |
1, 2, 3, 4, 5, 6, | |
1, 2, 3, 4, 5, 6, | |
2, 3, 4, 5, 6, | |
1, 3, 4, 5, 6, | |
1, 4, 5, 6 | |
]; | |
let resultElem = [ | |
1, 2, 3, 4, 5, 6, | |
1, 2, 3, 4, 5, 6, | |
0, 2, 3, 4, 5, 6, | |
1, 0, 3, 4, 5, 6, | |
1, 0, 0, 4, 5, 6 | |
]; | |
// verify our function | |
// check if array is identical https://stackoverflow.com/a/4025958 | |
function arraysEqual(arr1, arr2) { | |
if (arr1.length !== arr2.length) | |
return false; | |
for (var i = arr1.length; i--;) { | |
if (arr1[i] !== arr2[i]) | |
return false; | |
} | |
return true; | |
} | |
console.log(arraysEqual(similarFill(sourceElem, targetElem, 0), resultElem)) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment