How to move multiple elements to the beggining of the array?

I have a function that takes an array and string as arguments. The task is to chceck if the string occurs within the function and if does move to the first place of the array.

function moveToFirstPlace(['pizza', 'Pasta', 'Burger', 'PiZZa', 'pizzA'],'pizza')

in this example all pizzas have to be moved to the beggining of the array regardless of upper or lower letters.

One way to make it work is with looping thru the array and using the array methods of unshift and push after sanitizing the text you are searching for



Splice is perfect for your problem.

function moveToFirstPlace(arr, word) {
	arr.map( (elem, index) => {
  	  if (elem.toLowerCase() === word.toLowerCase()) {
    	    arr.splice(index, 1);
    	    arr.splice(0, 0, elem);
    }
  })
	return arr;
}

moveToFirstPlace(['pizza', 'Pasta', 'Burger', 'PiZZa', 'pizzA'],'pizza') 
//returns [ "pizzA", "PiZZa", "pizza", "Pasta", "Burger" ]

Map returns a new array with the elements returned in the callback- it is wasteful to use it in a way in which you are not creating a new array, and it is bad practice

Use forEach

1 Like