Home > Net >  Loop all elements within an array Javascript
Loop all elements within an array Javascript

Time:10-12

I am trying to create a new array which is a result of an old array which loops within itself and push all the elements to the new array starting from the giving index till it matches the length of old array.

Example

Old array ['yellow', 'red', 'green', 'blue', 'white', 'orange', 'black']

User enter any color name that is within the array like white

Expected output ['white', 'orange', 'black', 'yellow', 'red', 'green', 'blue']

function find_all_color() {
  var input = prompt("Enter any color");
  var colorArr = ['yellow', 'red','green', 'blue','white','orange', 'black']
  var arrIndex = colorArr.indexOf(input);
  var newArr = []
  for (let i = arrIndex; i <colorArr.length; i  ) {
    newArr.push(colorArr[i])
    }     console.log(newArr)

}

 find_all_color(); // output - ['white', 'orange', 'black']

CodePudding user response:

Why loop? You can remove the item where you find it in the array using splice and unshift it to the front

function find_all_color() {
  var input = prompt("Enter any color");
  var colorArr = ['yellow', 'red','green', 'blue','white','orange', 'black']
  var arrIndex = colorArr.indexOf(input);
  colorArr.splice(arrIndex,1)
  colorArr.unshift(input)
  console.log(colorArr)
}

 find_all_color(); // output - ['white', 'orange', 'black']

CodePudding user response:

Is it what you want?

The first item is the item passed as entry in the sortListOfColors function. All the other items are the following until the end of an array and then all the items starting from the first item in input array and until the input entry index.

const sortListOfColors = (input, entry) => [...input.slice(input.indexOf(entry)), ...input.slice(0, input.indexOf(entry))]


console.log(sortListOfColors(['yellow', 'red', 'green', 'blue', 'white', 'orange', 'black'], 'white')) // ['white', 'orange', 'black', 'yellow', 'red', 'green', 'blue']

CodePudding user response:

You can just use slice to create 2 shallow copies of your original array. You don't have to loop through your shallow copies, you can just use ES6 destructuring assignment to merge those arrays

var colorArr = ['yellow', 'red','green', 'blue','white','orange', 'black'];
var arrIndex = colorArr.indexOf('white');
var newArr = [...colorArr.slice(arrIndex), ...colorArr.slice(0, arrIndex)];

console.log(newArr);

  • Related