Skip to content
Advertisement

How to display elements of this array?

var arr = [2, 6, 4, 4, 4, 9]
var newArr = (arr.sort())

for (var i = 0; i < newArr.length; i++)
  if (newArr[i] == newArr[i + 1]) {
    var rem = [console.log(i)] //- (a)

  }
console.log(rem[0])

I want all the values of i for which the number is repeating in newArr array. Statement (a) gives me the indices and I want to store them in an array named rem. However console.log(rem[0]) is undefined. What can I do?

Advertisement

Answer

you mean this?

var arr = [2, 6, 4, 4, 4, 9]
var newArr = (arr.sort())
var rem = []; // create your rem array outside
for (var i = 0; i < newArr.length; i++) {
  if (newArr[i] == newArr[i + 1]) {
    rem.push(i); // if "i" matches your criteria, add it to the array.
  }
}
console.log(rem); // rem has the full list of indices
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement