code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

018 Array Replace

/**
 * 
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/* 
Given an array of integers, replace all the occurrences of elemToReplace with substitutionElem.

Example

For inputArray = [1, 2, 1], elemToReplace = 1 and substitutionElem = 3, the output should be arrayReplace(inputArray, elemToReplace, substitutionElem) = [3, 2, 3].

Input/Output 
*/


function arrayReplace(array, elemToReplace, substitutionElem) {
  array.forEach((element, index) => {
    if(element === elemToReplace){
      array[index] = substitutionElem
    }
  });
  return array
}

test('array Replace', () => {
  expect(arrayReplace([1,2,1],1,3)).toEqual([3,2,3])
});

Created 2019-12-09T02:17:09+05:30 · Edit