Skip to content

Instantly share code, notes, and snippets.

@ashnur
Created September 4, 2012 15:31
Show Gist options
  • Select an option

  • Save ashnur/3622440 to your computer and use it in GitHub Desktop.

Select an option

Save ashnur/3622440 to your computer and use it in GitHub Desktop.
diff between array of text values and object keys
var inp = [ 'a', 'b', 'c', 'f', 'g' ]
, out = [ 'd', 'e', 'c', 'b' ]
, res = []
;
function diff(inp, out){
var del = [], ign = [] , add = []
, i, t1 = out.length, t2
;
for ( i = 0; i < t1; i++ ) {
if ( ( t2 = inp.indexOf(out[i]) ) === -1 ) {
del.push(out[i])
} else {
ign.push(out[i])
inp.splice(t2,1)
}
}
add = inp
return [ del , ign , add ]
}
res = diff(inp, out)
console.log(res)
// res should be
// [
// [ 'd', 'e' ]
// , [ 'b', 'c' ]
// , [ 'a', 'f', 'g' ]
// ]
@gkatsev
Copy link
Copy Markdown

gkatsev commented Sep 4, 2012

out should probably be renamed current, as it is more descriptive of what it is.
t1 should be renamed closer to what it is.
I'd pull setting t2 out of inside the if and make it it's own statement. also, probably rename it to item or something.
instead of splicing input, i'd just push it into add instead, that way you don't mutate the input variable, though, that will require a bit more logic. It's a trade off.
out[i] should probably be pulled out to a temp variable as well since it's being used in several places.
returning a new array could be a performance issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment