0

I am facing an issue with array ordering sequence. Need your help for desired result.

var a = [0, 1, 2, 3, 4, 5, 6, 77, 7, 8, 9, 10, 11, 12, 35, 36, 43, 51, 72, 89, 95, 100];
var b = [6,5,7,8,0,800,46,1,2,3,12,47,100,95];
var c = [];

for (var i = 0; i <= (a.length) - 1; i++) {
  var res = b.indexOf(a[i]);
  if (res > -1) {
  	c.push(a[i]);
  }
}

document.write(c);
// I need same sequence of array B in reponse
// Desired Result
// 6,5,7,8,0,1,2,3,12,100,95

2
  • whats that with obj? you might simply do like var c = b.filter(f => a.includes(f)); Commented Jan 4, 2017 at 16:26
  • @Redu it was mistakenly added on question Commented Jan 5, 2017 at 6:26

1 Answer 1

4

Iterate array b instead of a:

var a = [0, 1, 2, 3, 4, 5, 6, 77, 7, 8, 9, 10, 11, 12, 35, 36, 43, 51, 72, 89, 95, 100];
var b = [6,5,7,8,0,800,46,1,2,3,12,47,100,95];
var c = [];

for (var i = 0; i < b.length; i++) {
  var res = a.indexOf(b[i]);
  if (res > -1) {
    c.push(b[i]);
  }
}

console.log(c.join(','));

A more functional solution is to use Array#filter on b:

var a = [0, 1, 2, 3, 4, 5, 6, 77, 7, 8, 9, 10, 11, 12, 35, 36, 43, 51, 72, 89, 95, 100];
var b = [6,5,7,8,0,800,46,1,2,3,12,47,100,95];

var c = b.filter(function(n) {
    return a.indexOf(n) !== -1;
});

console.log(c.join(','));

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

1 Comment

Thanks you save my day

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.