Wednesday, August 17, 2022

[FIXED] How to display elements of this array?

Issue

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?


Solution

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


Answered By - amin
Answer Checked By - Clifford M. (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.