Remove items from one array if not in the second array - javascript

I state that I have tried for a long time before writing this post.
For an InDesign script, I'm working with two array of ListItems. Now I'm trying to remove the items of one array that aren't in the second array, but i'm stuck.
Given that I use the following javascript code (it works great) to remove the equal items between the two arrays :
function check_dupli(arr_A, arr_B) {
for(var i = arr_B.length - 1; i >= 0; i--) {
for(var j = 0; j < arr_A.length; j++) {
if(arr_B[i] === arr_A[j]) {
arr_B.splice(i, 1);
}
}
}
arr_B.sort();
}
arr_A = ["a","b","d","f","g"]
arr_B = ["a","c","f","h"]
check_dupli(arr_A, arr_B) --> arr_B = ["c","h"]
check_dupli(arr_B, arr_A) --> arr_B = ["b","d","g"]
I thought to modify it in order to ignore the items not that are not in both arrays, and to obtain what I want, but something is going wrong because I also get the unwanted data :
function get_dupli(arr_A, arr_B, arr_C) {
for(var e = arr_B.length - 1; e >= 0; e--) {
for(var k = 0; k < arr_A.length; k++) {
if(arr_B[e] === arr_A[k]) {
arr_C.push(arr_B[e]);
}
}
}
arr_C.sort();
}
arr_A = ["a","b","d","f","g"]
arr_B = ["a","g","k"]
arr_C = ["h"]
get_dupli(arr_A, arr_B, arr_C) --> arr_C = ["a","g","h","k"] instead of --> ["a","g","h"]
get_dupli(arr_B, arr_A, arr_C) --> arr_C = ["a","b","d","f","g","h"] instead of --> ["a","g","h"]
Where I'm wrong? There is another way in pure javascript to solve the problem?
Thanks in advance for any help.

You can make use of Array.prototype.filter and Array.prototype.concat to simply it:
arr_A = ["a","b","d","f","g"]
arr_B = ["a","g","k"]
arr_C = ["h"]
function getCommonItems(arrayA, arrayB, result) {
result = result || [];
result = result.concat(arrayA.filter(function(item) {
return arrayB.indexOf(item) >= 0;
}));
return result.sort();
}
alert(getCommonItems(arr_A, arr_B, arr_C).join(", "));
alert(getCommonItems(arr_B, arr_A, arr_C).join(", "));
For the first scenario:
arr_A = ["a","b","d","f","g"]
arr_B = ["a","c","f","h"]
function getDifference(arrayA, arrayB, result) {
return arrayB.filter(function(item) {
return arrayA.indexOf(item) === -1;
}).sort();
}
alert(getDifference(arr_A, arr_B).join(", "));
alert(getDifference(arr_B, arr_A).join(", "));

Do it like this:
//the array which will loose some items
var ar1 = ["a", "b", "c"];
//the array which is the template
var ar2 = ["d", "a", "b"];
var tmpar = [];
for(var i = 0; i < ar1.length; i++){
if(ar2.indexOf(ar1[i]) !== -1){
tmpar.push(ar1[i]);
}
}
ar1 = tmpar;
alert(ar1);
We create a temporary array to store the valid values.
We make sure that the index of the value from the first array is not "-1". If it's "-1" the index is not found and therefore the value is not valid! We store everything which is not "-1" (so we store every valid value).

Array.prototype.contains = function ( object )
{
var i = 0, n = this.length;
for ( i = 0 ; i < n ; i++ )
{
if ( this[i] === object )
{
return true;
}
}
return false;
}
Array.prototype.removeItem = function(value, global) {
var idx;
var n = this.length;
while ( n-- ) {
if ( value instanceof RegExp && value.test ( this[n])
|| this[n] === value ) {
this.splice (n, 1 );
if ( !global ) return this;
}
}
return this;
};
arr_A = ["a","b","d","f","g"];
arr_B = ["a","c","f","h"];
var item
while ( item = arr_A.pop() ) {
arr_B.contains ( item ) && arr_B.removeItem ( item );
}
arr_B;

arr_A = ["a","b","d","f","g"];
arr_B = ["a","c","f","h"];
var newArr = [];
var item
while ( item = arr_B.shift() ) {
arr_A.contains ( item ) && newArr[ newArr.length ] = item ;
}
newArr;// ["a", "f"];

Opsss .... I believed I had given the answer and closed this post ... sorry !!!
Despite all the checks I made, the failure of the mine as your script was caused by a stupid mistake ... the array arr_A passed to the function was a modified copy of the original array.
Thank you all for your concern and help. Sorry again ...

Related

Find all sentence permutations with synonymous words? [duplicate]

This question already has answers here:
Cartesian product of multiple arrays in JavaScript
(35 answers)
Closed 1 year ago.
I'm having trouble coming up with code to generate combinations from n number of arrays with m number of elements in them, in JavaScript. I've seen similar questions about this for other languages, but the answers incorporate syntactic or library magic that I'm unsure how to translate.
Consider this data:
[[0,1], [0,1,2,3], [0,1,2]]
3 arrays, with a different number of elements in them. What I want to do is get all combinations by combining an item from each array.
For example:
0,0,0 // item 0 from array 0, item 0 from array 1, item 0 from array 2
0,0,1
0,0,2
0,1,0
0,1,1
0,1,2
0,2,0
0,2,1
0,2,2
And so on.
If the number of arrays were fixed, it would be easy to make a hard coded implementation. But the number of arrays may vary:
[[0,1], [0,1]]
[[0,1,3,4], [0,1], [0], [0,1]]
Any help would be much appreciated.
Here is a quite simple and short one using a recursive helper function:
function cartesian(...args) {
var r = [], max = args.length-1;
function helper(arr, i) {
for (var j=0, l=args[i].length; j<l; j++) {
var a = arr.slice(0); // clone arr
a.push(args[i][j]);
if (i==max)
r.push(a);
else
helper(a, i+1);
}
}
helper([], 0);
return r;
}
Usage:
cartesian([0,1], [0,1,2,3], [0,1,2]);
To make the function take an array of arrays, just change the signature to function cartesian(args) instead of using rest parameter syntax.
I suggest a simple recursive generator function:
// JS
function* cartesianIterator(head, ...tail) {
const remainder = tail.length ? cartesianIterator(...tail) : [[]];
for (let r of remainder) for (let h of head) yield [h, ...r];
}
// get values:
const cartesian = items => [...cartesianIterator(items)];
console.log(cartesian(input));
// TS
function* cartesianIterator<T>(items: T[][]): Generator<T[]> {
const remainder = items.length > 1 ? cartesianIterator(items.slice(1)) : [[]];
for (let r of remainder) for (let h of items.at(0)!) yield [h, ...r];
}
// get values:
const cartesian = <T>(items: T[][]) => [...cartesianIterator(items)];
console.log(cartesian(input));
You could take an iterative approach by building sub arrays.
var parts = [[0, 1], [0, 1, 2, 3], [0, 1, 2]],
result = parts.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
console.log(result.map(a => a.join(', ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
After doing a little research I discovered a previous related question:
Finding All Combinations of JavaScript array values
I've adapted some of the code from there so that it returns an array of arrays containing all of the permutations:
function(arraysToCombine) {
var divisors = [];
for (var i = arraysToCombine.length - 1; i >= 0; i--) {
divisors[i] = divisors[i + 1] ? divisors[i + 1] * arraysToCombine[i + 1].length : 1;
}
function getPermutation(n, arraysToCombine) {
var result = [],
curArray;
for (var i = 0; i < arraysToCombine.length; i++) {
curArray = arraysToCombine[i];
result.push(curArray[Math.floor(n / divisors[i]) % curArray.length]);
}
return result;
}
var numPerms = arraysToCombine[0].length;
for(var i = 1; i < arraysToCombine.length; i++) {
numPerms *= arraysToCombine[i].length;
}
var combinations = [];
for(var i = 0; i < numPerms; i++) {
combinations.push(getPermutation(i, arraysToCombine));
}
return combinations;
}
I've put a working copy at http://jsfiddle.net/7EakX/ that takes the array you gave earlier ([[0,1], [0,1,2,3], [0,1,2]]) and outputs the result to the browser console.
const charSet = [["A", "B"],["C", "D", "E"],["F", "G", "H", "I"]];
console.log(charSet.reduce((a,b)=>a.flatMap(x=>b.map(y=>x+y)),['']))
Just for fun, here's a more functional variant of the solution in my first answer:
function cartesian() {
var r = [], args = Array.from(arguments);
args.reduceRight(function(cont, factor, i) {
return function(arr) {
for (var j=0, l=factor.length; j<l; j++) {
var a = arr.slice(); // clone arr
a[i] = factor[j];
cont(a);
}
};
}, Array.prototype.push.bind(r))(new Array(args.length));
return r;
}
Alternative, for full speed we can dynamically compile our own loops:
function cartesian() {
return (cartesian.cache[arguments.length] || cartesian.compile(arguments.length)).apply(null, arguments);
}
cartesian.cache = [];
cartesian.compile = function compile(n) {
var args = [],
indent = "",
up = "",
down = "";
for (var i=0; i<n; i++) {
var arr = "$"+String.fromCharCode(97+i),
ind = String.fromCharCode(105+i);
args.push(arr);
up += indent+"for (var "+ind+"=0, l"+arr+"="+arr+".length; "+ind+"<l"+arr+"; "+ind+"++) {\n";
down = indent+"}\n"+down;
indent += " ";
up += indent+"arr["+i+"] = "+arr+"["+ind+"];\n";
}
var body = "var res=[],\n arr=[];\n"+up+indent+"res.push(arr.slice());\n"+down+"return res;";
return cartesian.cache[n] = new Function(args, body);
}
var f = function(arr){
if(typeof arr !== 'object'){
return false;
}
arr = arr.filter(function(elem){ return (elem !== null); }); // remove empty elements - make sure length is correct
var len = arr.length;
var nextPerm = function(){ // increase the counter(s)
var i = 0;
while(i < len)
{
arr[i].counter++;
if(arr[i].counter >= arr[i].length){
arr[i].counter = 0;
i++;
}else{
return false;
}
}
return true;
};
var getPerm = function(){ // get the current permutation
var perm_arr = [];
for(var i = 0; i < len; i++)
{
perm_arr.push(arr[i][arr[i].counter]);
}
return perm_arr;
};
var new_arr = [];
for(var i = 0; i < len; i++) // set up a counter property inside the arrays
{
arr[i].counter = 0;
}
while(true)
{
new_arr.push(getPerm()); // add current permutation to the new array
if(nextPerm() === true){ // get next permutation, if returns true, we got them all
break;
}
}
return new_arr;
};
Here's another way of doing it. I treat the indices of all of the arrays like a number whose digits are all different bases (like time and dates), using the length of the array as the radix.
So, using your first set of data, the first digit is base 2, the second is base 4, and the third is base 3. The counter starts 000, then goes 001, 002, then 010. The digits correspond to indices in the arrays, and since order is preserved, this is no problem.
I have a fiddle with it working here: http://jsfiddle.net/Rykus0/DS9Ea/1/
and here is the code:
// Arbitrary base x number class
var BaseX = function(initRadix){
this.radix = initRadix ? initRadix : 1;
this.value = 0;
this.increment = function(){
return( (this.value = (this.value + 1) % this.radix) === 0);
}
}
function combinations(input){
var output = [], // Array containing the resulting combinations
counters = [], // Array of counters corresponding to our input arrays
remainder = false, // Did adding one cause the previous digit to rollover?
temp; // Holds one combination to be pushed into the output array
// Initialize the counters
for( var i = input.length-1; i >= 0; i-- ){
counters.unshift(new BaseX(input[i].length));
}
// Get all possible combinations
// Loop through until the first counter rolls over
while( !remainder ){
temp = []; // Reset the temporary value collection array
remainder = true; // Always increment the last array counter
// Process each of the arrays
for( i = input.length-1; i >= 0; i-- ){
temp.unshift(input[i][counters[i].value]); // Add this array's value to the result
// If the counter to the right rolled over, increment this one.
if( remainder ){
remainder = counters[i].increment();
}
}
output.push(temp); // Collect the results.
}
return output;
}
// Input is an array of arrays
console.log(combinations([[0,1], [0,1,2,3], [0,1,2]]));
You can use a recursive function to get all combinations
const charSet = [["A", "B"],["C", "D", "E"],["F", "G", "H", "I"]];
let loopOver = (arr, str = '', final = []) => {
if (arr.length > 1) {
arr[0].forEach(v => loopOver(arr.slice(1), str + v, final))
} else {
arr[0].forEach(v => final.push(str + v))
}
return final
}
console.log(loopOver(charSet))
This code can still be shorten using ternary but i prefer the first version for readability 😊
const charSet = [["A", "B"],["C", "D", "E"],["F", "G", "H", "I"]];
let loopOver = (arr, str = '') => arr[0].map(v => arr.length > 1 ? loopOver(arr.slice(1), str + v) : str + v).flat()
console.log(loopOver(charSet))
Another implementation with ES6 recursive style
Array.prototype.cartesian = function(a,...as){
return a ? this.reduce((p,c) => (p.push(...a.cartesian(...as).map(e => as.length ? [c,...e] : [c,e])),p),[])
: this;
};
console.log(JSON.stringify([0,1].cartesian([0,1,2,3], [[0],[1],[2]])));

Finding an Object's value from an Array

Is there a simpler (or more efficient) way of achieving the following:
var _dataObjects = [{id:0, data:"data0", nextID:1},
{id:1, data:"data1", nextID:2},
{id:2, data:"data2", nextID:3} .. etc.];
generateNextPieceOfData();
function generateNextPieceOfData(){
var len = _dataObjects.length;
for ( var i = 0; i < len; i ++ ) {
var nextDataID = _dataObjects[i].nextID;
var nextData;
for ( var j = 0; j < len; j ++ ) {
if( _dataObjects[j].id == nextDataID ){
nextData = _dataObjects[j].data;
break;
}
}
}
}
The above example is abstracted from the problem I'm having and I realise the ID numbers are sequential in this instance but in the real problem nextID numbers do not run sequentially.
Thanks in advance.
Use the right data structure for your problem. Since you want to find an object by ID, create a hash map with the IDs as keys and objects as values:
var object_map = {};
for(var i = 0, l = _dataObjects.length; i < l; i++) {
objects[_dataObjects[i].id] = _dataObjects[i];
}
Then getting the next object is simply:
var next_object = object_map[someObject.nextID];
You still have iterate until some terminal condition is met though. For example:
function generatePath(id_a, id_b) {
var obj = object_map[id_a];
var path = [obj];
while (obj && obj.id !== id_b) {
obj = object_map[obj.nextID];
path.push(obj);
}
return path;
}
If your code works sequentially only, then you can sort the items by id or whatever and your code should work right? Try this:
_dataObjects = _dataObjects.sort(function(a, b) {
return a.id > b.id;
});

String split and count the number of occurrences and also

I have a string
var stringIHave = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$";
How to get the count of the number of occurrences of each entry, The occurrence I get, is from a JSON like Java = 8 and etc...
First of all you need to split your srting to array:
var keywordsArr = stringIHave.split( '$$' );
then you need to have an object for example to store counts:
var occur = {};
and then just create simple for loop to count all occurrences:
for( var i = 0; i < keywordsArr.length; i++ ) {
occur[ keywordsArr[ i ] ] = ( occur[ keywordsArr[ i ] ] || 0 ) + 1;
}
now your object occur will have names as keys and count as values.
See jsFiddle demo.
Also as you have at end of your string $$ you maybe will need to remove last item from keywordsArr so just do after split function call:
keywordsArr.pop();
See demo without last element.
So final code will be like:
var stringIHave = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$",
keywordsArr = stringIHave.split( '$$' ),
occur = {};
keywordsArr.pop();
for( var i = 0; i < keywordsArr.length; i++ ) {
occur[ keywordsArr[ i ] ] = ( occur[ keywordsArr[ i ] ] || 0 ) + 1;
}
for( var key in occur ) {
document.write( key + ' - ' + occur[key] + '<br/>' );
} ​
I'd suggest the following:
function stringCount(haystack, needle) {
if (!needle || !haystack) {
return false;
}
else {
var words = haystack.split(needle),
count = {};
for (var i = 0, len = words.length; i < len; i++) {
if (count.hasOwnProperty(words[i])) {
count[words[i]] = parseInt(count[words[i]], 10) + 1;
}
else {
count[words[i]] = 1;
}
}
return count;
}
}
console.log(stringCount("Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$", '$$'));
​
JS Fiddle demo.
References:
Object.hasOwnProperty().
parseInt().
String.split().
It's not entirely clear what final objective is. Following creates an object from string that looks like
Object created:
{
"Java": 8,
"jQuery": 4,
"Hibernate": 1,
"Spring": 1,
"Instagram": 1
}
JS:
var str = 'Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$';
var arr = str.split('$$')
var obj = {};
for (i = 0; i < arr.length; i++) {
if (arr[i] != '') {
if (!obj[arr[i]]) {
obj[arr[i]] = 0;
}
obj[arr[i]]++;
}
}
You can loop over the object to get all values or simply look up one value
var jQueryOccurences= obj['jQuery'];
DEMO: http://jsfiddle.net/25hBV/1/
Now a days you can do
const str = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$";
var result = str.split("$$").reduce(function(acc, curr) {
curr && (acc[curr] = (acc[curr] + 1) || 1);
return acc
}, {});
console.log(result);
Split the string into an array, and putting the array into an object takes care of duplicates and counts occurences as key/value pairs in the object, see fiddle!
var stringIHave = "Java$$Java$$jQuery$$Java$$jQuery$$Java$$Java$$Java$$Hibernate$$Java$$Java$$Spring$$Instagram$$jQuery$$jQuery$$",
s = stringIHave.split('$$');
obj = {};
for (var i=s.length; i--;) {
obj[s[i]] = (s[i] in obj) ? obj[s[i]]+1 : 1;
}
// obj.Java == 8
FIDDLE
If you want it short and sweet:
// variable declarations
var arParts = stringIHave.match(/\w+/g),
result = {},
i = 0,
item;
// Copy the array to result object
while (item = arParts[i++]) result[item] = (result[item] || 0 ) + 1;
demo

The best way to remove array element by value

I have an array like this
arr = ["orange","red","black","white"]
I want to augment the array object defining a deleteElem() method which acts like this:
arr2 = arr.deleteElem("red"); // ["orange","black","white"] (with no hole)
What is the best way to accomplish this task using just the value parameter (no index)?
Here's how it's done:
var arr = ["orange","red","black","white"];
var index = arr.indexOf("red");
if (index >= 0) {
arr.splice( index, 1 );
}
This code will remove 1 occurency of "red" in your Array.
Back when I was new to coding I could hardly tell what splice was doing, and even today it feels less readable.
But readability counts.
I would rather use the filter method like so:
arr = ["orange","red","black","white","red"]
arr = arr.filter(val => val !== "red");
console.log(arr) // ["orange","black","white"]
Note how all occurrences of "red" are removed from the array.
From there, you can easily work with more complex data such as array of objects.
arr = arr.filter(obj => obj.prop !== "red");
There is an underscore method for this, http://underscorejs.org/#without
arr = ["orange","red","black","white"];
arr = _.without(arr, "red");
The trick is to go through the array from end to beginning, so you don't mess up the indices while removing elements.
var deleteMe = function( arr, me ){
var i = arr.length;
while( i-- ) if(arr[i] === me ) arr.splice(i,1);
}
var arr = ["orange","red","black", "orange", "white" , "orange" ];
deleteMe( arr , "orange");
arr is now ["red", "black", "white"]
Array.prototype.deleteElem = function(val) {
var index = this.indexOf(val);
if (index >= 0) this.splice(index, 1);
return this;
};
var arr = ["orange","red","black","white"];
var arr2 = arr.deleteElem("red");
My approach, let's see what others have to say. It supports an "equals" method as well.
// Remove array value
// #param {Object} val
Array.prototype.removeByValue = function (val) {
for (var i = 0; i < this.length; i++) {
var c = this[i];
if (c == val || (val.equals && val.equals(c))) {
this.splice(i, 1);
break;
}
}
};
Read https://stackoverflow.com/a/3010848/356726 for the impact on iterations when using prototype with Array.
Or simply check all items, create a new array with non equal and return it.
var arr = ['orange', 'red', 'black', 'white'];
console.info('before: ' + JSON.stringify(arr));
var deleteElem = function ( val ) {
var new_arr = [];
for ( var i = 0; i < this.length; i++ ) {
if ( this[i] !== val ) {
new_arr.push(this[i]);
}
}
return new_arr;
};
arr = deleteElem('red');
console.info('after: ' + JSON.stringify(arr));
http://jsfiddle.net/jthavn3m/
The best way is to use splice and rebuild new array, because after splice, the length of array does't change.
Check out my answer:
function remove_array_value(array, value) {
var index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
reindex_array(array);
}
}
function reindex_array(array) {
var result = [];
for (var key in array) {
result.push(array[key]);
}
return result;
}
example:
var example_arr = ['apple', 'banana', 'lemon']; // length = 3
remove_array_value(example_arr, 'banana');
banana is deleted and array length = 2
If order the array (changing positions) won't be a problem you can solve like:
var arr = ["orange","red","black","white"];
arr.remove = function ( item ) {
delete arr[item];
arr.sort();
arr.pop();
console.log(arr);
}
arr.remove('red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here you go:
arr.deleteElem = function ( val ) {
for ( var i = 0; i < this.length; i++ ) {
if ( this[i] === val ) {
this.splice( i, 1 );
return i;
}
}
};
Live demo: http://jsfiddle.net/4vaE2/3/
The deleteElem method returns the index of the removed element.
var idx = arr.deleteElem( 'red' ); // idx is 1

fastest way to detect if duplicate entry exists in javascript array?

var arr = ['test0','test2','test0'];
Like the above,there are two identical entries with value "test0",how to check it most efficiently?
If you sort the array, the duplicates are next to each other so that they are easy to find:
arr.sort();
var last = arr[0];
for (var i=1; i<arr.length; i++) {
if (arr[i] == last) alert('Duplicate : '+last);
last = arr[i];
}
This will do the job on any array and is probably about as optimized as possible for handling the general case (finding a duplicate in any possible array). For more specific cases (e.g. arrays containing only strings) you could do better than this.
function hasDuplicate(arr) {
var i = arr.length, j, val;
while (i--) {
val = arr[i];
j = i;
while (j--) {
if (arr[j] === val) {
return true;
}
}
}
return false;
}
There are lots of answers here but not all of them "feel" nice... So I'll throw my hat in.
If you are using lodash:
function containsDuplicates(array) {
return _.uniq(array).length !== array.length;
}
If you can use ES6 Sets, it simply becomes:
function containsDuplicates(array) {
return array.length !== new Set(array).size
}
With vanilla javascript:
function containsDuplicates(array) {
return array
.sort()
.some(function (item, i, items) {
return item === items[i + 1]
})
}
However, sometimes you may want to check if the items are duplicated on a certain field.
This is how I'd handle that:
containsDuplicates([{country: 'AU'}, {country: 'UK'}, {country: 'AU'}], 'country')
function containsDuplicates(array, attribute) {
return array
.map(function (item) { return item[attribute] })
.sort()
.some(function (item, i, items) {
return item === items[i + 1]
})
}
Loop stops when found first duplicate:
function has_duplicates(arr) {
var x = {}, len = arr.length;
for (var i = 0; i < len; i++) {
if (x[arr[i]]) {
return true;
}
x[arr[i]] = true;
}
return false;
}
Edit (fix 'toString' issue):
function has_duplicates(arr) {
var x = {}, len = arr.length;
for (var i = 0; i < len; i++) {
if (x[arr[i]] === true) {
return true;
}
x[arr[i]] = true;
}
return false;
}
this will correct for case has_duplicates(['toString']); etc..
var index = myArray.indexOf(strElement);
if (index < 0) {
myArray.push(strElement);
console.log("Added Into Array" + strElement);
} else {
console.log("Already Exists at " + index);
}
You can convert the array to to a Set instance, then convert to an array and check if the length is same before and after the conversion.
const hasDuplicates = (array) => {
const arr = ['test0','test2','test0'];
const uniqueItems = new Set(array);
return array.length !== uniqueItems.size();
};
console.log(`Has duplicates : ${hasDuplicates(['test0','test2','test0'])}`);
console.log(`Has duplicates : ${hasDuplicates(['test0','test2','test3'])}`);
Sorting is O(n log n) and not O(n). Building a hash map is O(n). It costs more memory than an in-place sort but you asked for the "fastest." (I'm positive this can be optimized but it is optimal up to a constant factor.)
function hasDuplicate(arr) {
var hash = {};
var hasDuplicate = false;
arr.forEach(function(val) {
if (hash[val]) {
hasDuplicate = true;
return;
}
hash[val] = true;
});
return hasDuplicate;
}
It depends on the input array size. I've done some performance tests with Node.js performance hooks and found out that for really small arrays (1,000 to 10,000 entries) Set solution might be faster. But if your array is bigger (like 100,000 elements) plain Object (i. e. hash) solution becomes faster. Here's the code so you can try it out for yourself:
const { performance } = require('perf_hooks');
function objectSolution(nums) {
let testObj = {};
for (var i = 0; i < nums.length; i++) {
let aNum = nums[i];
if (testObj[aNum]) {
return true;
} else {
testObj[aNum] = true;
}
}
return false;
}
function setSolution(nums) {
let testSet = new Set(nums);
return testSet.size !== nums.length;
}
function sortSomeSolution(nums) {
return nums
.sort()
.some(function (item, i, items) {
return item === items[i + 1]
})
}
function runTest(testFunction, testArray) {
console.log(' Running test:', testFunction.name);
let start = performance.now();
let result = testFunction(testArray);
let end = performance.now();
console.log(' Duration:', end - start, 'ms');
}
let arr = [];
let setSize = 100000;
for (var i = 0; i < setSize; i++) {
arr.push(i);
}
console.log('Set size:', setSize);
runTest(objectSolution, arr);
runTest(setSolution, arr);
runTest(sortSomeSolution, arr);
On my Lenovo IdeaPad with i3-8130U Node.js v. 16.6.2 gives me following results for the array of 1,000:
results for the array of 100,000:
Assuming all you want is to detect how many duplicates of 'test0' are in the array. I guess an easy way to do that is to use the join method to transform the array in a string, and then use the match method.
var arr= ['test0','test2','test0'];
var str = arr.join();
console.log(str) //"test0,test2,test0"
var duplicates = str.match(/test0/g);
var duplicateNumber = duplicates.length;
console.log(duplicateNumber); //2

Categories

Resources