0

I am trying to find an element in the array. Here is the fiddle:

var selectedVals = [630, 85];
var registeredVals = [17, 630, 85];
var newList = [];

$(selectedVals).each(function () {
    //registeredVals.splice($.inArray(this, registeredVals), 1);
    var num = this;
    alert("Value="+ num + " Array=" + registeredVals);
    //alert(registeredVals.indexOf(num));
    alert($.inArray(this, registeredVals));

    if($.inArray(this, registeredVals) == -1)
         newList.push(this);
    })

https://jsfiddle.net/programmedprojects/7m9zrjwL/

I tried .indexOf and $.inArray to find the element in loop.

Shouldn't the index be greater than -1 as the element is in the array?

2
  • What are you trying to find? What is the expected output? Commented Apr 6, 2018 at 17:37
  • Basically, i am trying to find the duplicates. I just opted this way as i didn't find the desired behavior. There are two multiselect list boxes, on a button click, i want to move the items from one to another without removing from the parent and not add duplicates to the second list Commented Apr 6, 2018 at 17:40

1 Answer 1

1

If you want to know what elements present on both selectedVals and registeredVals, you can use filter() and use includes() to check if a variable exists on an array.

var selectedVals = [630, 85, 99];
var registeredVals = [17, 630, 85];

var newList = selectedVals.filter(o => registeredVals.includes(o));

console.log(newList);

Without ES6

var selectedVals = [630, 85, 99];
var registeredVals = [17, 630, 85];
var newList = [];

for (var i = 0; i < selectedVals.length; i++) {
  if (registeredVals.indexOf(selectedVals[i]) !== -1) newList.push(selectedVals[i]);
}

console.log(newList);

Sign up to request clarification or add additional context in comments.

3 Comments

I tried this but looks like IE doesn't support => and i get SCRIPT1002: Syntax error. Even the above doesn't run on IE 11.
Thanks for the solution. But what was wrong with $.each loop? Why did the index returned wrong?
I think the whole use of jQuery is wrong.You should use $.each instead of $(selectedVals)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.