2

I'm using labels in my code. But javascript keeps complaining 'label is not a statement.'

function firstDuplicate(a) {
  array1 = [];
  b = a;
  var val;
  var valIndex;
  var iCount = 0;

  a.forEach(function(aLoop, aIndex) {
    b.forEach(function(bLoop, bIndex) {
      if (bLoop == aLoop) {
        val = bLoop;
        iCount = iCount++;
        valIndex = bIndex;
      } else { //I want to move evaluation to where I have label 'loop1'
        break loop1;
      }
    });
    obj = {
      val: val,
      index: valIndex,
      count: iCount
    };
    array1.push(obj);
    val = 0;
    iCount = 0;
    valIndex = 0;
    loop1:
  });
  return array1;
}

console.log(firstDuplicate([2, 1, 3, 5, 3, 2]));

actual result is crashing; expecting js object be populated with 1) elements that occur > 1; index of the last occurence of the element; and count

Eddie
  • 26,593
  • 6
  • 36
  • 58
jack kemp
  • 21
  • 2
  • You can only use `break` to break out of a `for` or `while` loop. You can't use it to break out of a function. – Barmar Apr 21 '19 at 06:41
  • loop1: at the end could be the problem but not sure. – Daniel Kemeny Apr 21 '19 at 06:43
  • Why do you want to use labels? Is there a specific requirement, or can you write that code without them? – RaidenF Apr 21 '19 at 06:47
  • Thank you much! I only use label as a means to an end--i.e., I thought that was a way to break out of a loop. But per response here, you can't break out of a function. Apologies for the elementary questions I asked. – jack kemp Apr 21 '19 at 07:17

1 Answers1

0

You can't break out of a Array.forEach function.

  • You are using the post increment operator which won't work in this case. Here iCount = iCount++; will evaluate iCount as 0.
  • You also need to find the previous object inserted when there is a duplicate found in array1 and then increment its count. You can do this by using Array.find.
  • If a duplicate is found by comparing the aIndex and bIndex then we are pushing a new object into array1 with count as 1. If it is again encountered later we simply find the inserted object and increase the count and record the index in an array.

function firstDuplicate(a) {
  array1 = [];
  a.forEach(function(aLoop, aIndex) {
    a.forEach(function(bLoop, bIndex) {
      if (bIndex > aIndex && bLoop === aLoop) {
          let dup = array1.find(o => o.val === bLoop);
          if(!dup){
           obj = {
             val: bLoop,
             index: [aIndex, bIndex],
             count: 1
           };
           array1.push(obj);
          }else{
           dup.count = dup.count + 1;
           dup.index = !dup.index.includes(bIndex) ? [bIndex].concat(dup.index) : dup.index;
          }
      } 
    });
  });
  return array1;
}

console.log(firstDuplicate([2, 1, 3, 5, 3, 2, 2, 3]));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44