Comparing arguments with an arguments in JavaScript - javascript

Please help me with this code; I am trying to compare arguments with an array elements and return when it matches, I don't know what is wrong with this code, it returns 1 rather than an array , thanks.
const removeFromArray = function() {
var delArgs = [] ;
//convert the arguments to an array called 'args'.
var args = Array.from(arguments);
var Arr = args[0];
//using foreach() and forloop to compare arguments with Arr elements.
Arr.forEach(function(x){
for (var j=1 ; j < args.length ; j++){
if(x == args[j]){
delArgs = delArgs.push(x);
}
}
});
return delArgs;
}
removeFromArray([1,2,3,4,5,6] , 5);
1

delArgs = delArgs.push(x);
You're overwriting delArgs with the return value from push, which is the new length of the array.
Don't do that.

since the question is already answered, you could use this for shorter code
const removeFromArray = (array, ...args) => {
return args.filter( arg => array.includes(arg) )
}
console.log(removeFromArray([1, 2, 3, 4, 5, 6], 5,6));

Related

Remove duplicates from an array within an array [duplicate]

Input:
[[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]]
The output I want:
[[-1,-1,2],[-1,0,1]]
Any other ideas except this one?
Thanks
You won't really get around stringifying the arrays, as that's the simplest (and reasonably fast) way to compare them by value. So I'd go for
Array.from(new Set(input.map(JSON.stringify)), JSON.parse)
See also Remove Duplicates from JavaScript Array for other approaches, though most of them will require two values to be comparable by ===.
Magic
d.filter(( t={}, a=> !(t[a]=a in t) ));
I assume your input data are in array d. Explanation here.
let d = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]];
var r = d.filter((t={},a=>!(t[a]=a in t)));
console.log(JSON.stringify(r));
There's already a good utility for that, try Lodash, one of the function of it is _.uniqWith, with that function you can do the following.
<script src="/path/to/lodash.js"></script>
<script>
var aa = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]];
console.log(aa);
console.log(_.uniqWith(aa,_.isEqual));
</script>
You can create a hashMap and save values in it. This will always hold last value.
var data = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]]
var hashMap = {}
data.forEach(function(arr){
// If your subArrays can be in any order, you can use .sort to have consistant order
hashMap[arr.join("|")] = arr;
});
var result = Object.keys(hashMap).map(function(k){
return hashMap[k]
})
console.log(result)
jsfiddle
Borrowing the array comparison code from this post
// Warn if overriding existing method
if(Array.prototype.equals)
console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
var old = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]], n = [];
while(old.length) {
var arr = old.shift(), matched = false;
for(var i = 0, len = n.length; i < len; i++) {
if (arr.equals(n[i])) {
matched = true;
break;
}
}
if (!matched) {
n.push(arr);
}
}
const removeDuplicates = (arr = []) => {
const map = new Map();
arr.forEach((x) => map.set(JSON.stringify(x), x));
arr = [...map.values()];
return arr;
};
console.log(
removeDuplicates([
[1, 1, 6],
[1, 2, 5],
[1, 7],
[1, 2, 5],
[1, 7],
[2, 6],
])
);
// we can use simple JS object also to store unique elements like { "[1, 1, 6]" : [1, 1, 6] }
//resource - https://hackinbits.com/articles/how-to-iterate-a-map-in-javascript---map-part-2

Can I modify a for...of loop's variable? [duplicate]

I'm trying to square each number in an array and my original code didn't work. I looked up another way to do it, but I'd like to know WHY the original code didn't work.
Original code:
function(arr) {
ret= [];
for (var i = 0, len = arr.length; i < len; i++) {
root = Math.sqrt(arr[i]);
ret.push(root);
}
return ret;
}
Working Code:
function(arr) {
ret= [];
for (var i = 0, len = arr.length; i < len; i++) {
ret.push(arr[i] * arr[i]);
}
return ret;
}
Math.sqrt gives you square root not square of a number. Use Math.pow with second argument of 2.
How about that ?
function (arr) {
return arr.map(function (x) {
return Math.pow(x, 2);
});
}
Array.map(func) applies the function to each element of the map and returns the array composed of the new values.
Math.pow(base, exp) raises base to its exp power.
The first sample is taking the square root, not squaring the value. To square you want to use
Math.pow(arr[i],2);
Here is how it can be done, using a simple method called .forEach
var numbers = [1,2,3,4,5,6,7,8];
numbers.forEach(function(element, index, array){
array[index] = element* element;
});
console.log(numbers);
Best way to Square each number in an array in javascript
Array.prototype.square = function () {
var arr1 = [];
this.map(function (obj) {
arr1.push(obj * obj);
});
return arr1;
}
arr = [1, 6, 7, 9];
console.log(arr.square());
arr1 = [4, 6, 3, 2];
console.log(arr1.square())
Here is the function write with ES6 Exponentiation (**):
let arr = [1, 6, 7, 9];
let result = arr.map(x => x ** 2);
console.log(result);
The original code is taking the square root of the value. The second version is multiplying the value with itself (squaring it). These are inverse operations
I hope this answers your question
const numbers = [1,2,3,4,5,6,7,8,9];
for(let squareIt of numbers){
console.log(Math.pow(squareIt, 2));
}
Resolved by kiss-barnabas
Use embedded for , for pretty syntax :
var arr=[1,2,3,4] ;
[for (i of arr) i*i ];
//OUT : > [1,4,9,16]
Declarative Programming :)
let list = [1,2,3,4,5,6,7,8,9,10];
let result = list.map(x => x*x);
console.log(result);
Avoid unnecessary loops, use map()function
let array = [1,2,3,4,5];
function square(a){ // function to find square
return a*a;
}
arrSquare = array.map(square); //array is the array of numbers and arrSquare will be an array of same length with squares of every number
You can make the code shorter like this:
let array = [1,2,3,4,5];
arrSquare = array.map(function (a){return a*a;});
let arr = [1, 2, 3];
let mapped = arr.map(x => Math.pow(x, 2));
console.log(mapped);
This should work.
let kiss=[3,4,5,6];
let arra=[];
for(o in kiss){
arra.push(kiss[o]*kiss[o])
}
console.log(kiss=arra)
using array square root of the first number is equal to the cube root of the second number
function SquareAndCube(arr) {
let newarr = [];
for(i=0 ; i<arr.length; i++) {
if(Math.sqrt(arr[0])/2 === Math.cbrt(arr[1])/2 ) {
return true;
} else return false;
}
}
console.log(SquareAndCube([36, 215]))
This should work with the .map() method:
const number = [2, 6, 6, 2, 8, 10];
const squareNumber = number.map(num => num*num);
console.log(squareNumber);
function squareDigits(num){
//may the code be with you
var output = [];
var splitNum = num.toString();
for(var i = 0; i < splitNum.length; i++){
output.push(splitNum.charAt(i))
}
function mapOut(){
var arr = output;
return arr.map(function(x){
console.log(Math.pow(x, 2));
})
}
mapOut();
}
squareDigits(9819);
This should work
This will work
const marr = [1,2,3,4,5,6,7,8,9,10];
console.log(marr.map((x) => Math.pow(x, 2)));
function map(square,a) {
var result = [];
for(var i=0;i<=a.length-1;i++)
result[i]=square(a[i]);
return result;
}
var square = function(x) {
return x*x;
}
var value=[1,2,3,4];
var final= map(square,value);
console.log(final);
You can also try the above code snippet.

how to print a unique number in a array

The problem is to find the unique number in a array such as [2,2,2,5].
The output should be 5 as it is the 1 unique element in the array.
I have attempted this:
function findUniq(arr) {
var b= arr[0];
var c;
for(var i=0; i<arr.length; i++)
{
if(arr[i]===b )
{
b=arr[i]
}
else
{
c=arr[i];
}
}
return c
console.log(findUniq([3, 5, 3, 3, 3]))
This works fine unless the unique number is the first element in the array. How do I fix this?
You can use indexOf and lastIndexOf to see if a value occurs more than once in the array (if it does, they will be different), and if so, it is not the unique value. Use filter to process the array:
let array = [2,2,2,5];
console.log(array.filter(v => array.indexOf(v) === array.lastIndexOf(v)));
array = [5,3,3,3,3];
console.log(array.filter(v => array.indexOf(v) === array.lastIndexOf(v)));
array = [4,4,5,4];
console.log(array.filter(v => array.indexOf(v) === array.lastIndexOf(v)));
You can create a recursive function that will take the first element of the array and see if it exists in the rest of it, if it does, it will take the next element and do the same, return the element if it doesn't exist in the rest of the array :
const arr = [3, 3, 3, 5, 3];
const find = arr => {
const [f, ...rest] = arr;
if(rest.includes(f))
return find(rest);
else
return f;
}
const result = find(arr);
console.log(result);
Note that this will return the last element if all of them are the same [3,3,3] will return 3
Try something like this using a set, which only stores unique elements:
var set = new Set(arr);
// count instances of each element in set
result = {};
for(var i = 0; i < a.length; ++i) {
if(!result[arr[i]])
result[arr[i]] = 0;
++result[arr[i]];
}
for (var value in result) {
if (value == 1) {
return value;
}
}
// if there isn't any
return false;
This should work, please tell me if it doesn't.
This is another implementation that is surely less efficient than that of #Nick's, but it is a valid algorithm anyway:
function findUniq(arr) {
var elemCount = new Map();
var uniq = [];
// Initialize elements conts
for (var k of arr.values()) {
elemCount.set(k, 0);
}
// Count elements
for (var k of arr.values()) {
elemCount.set(k, elemCount.get(k) + 1);
}
// Add uniq elements to array
for (var [k, v] of elemCount.entries()) {
if (v === 1) uniq.push(k);
}
return uniq;
}
console.log(findUniq([3, 5, 3, 3, 3]))
if you prefer .reduce over .map for your use case (for performance/etc. reasons):
function existance(data) {
return data.reduce((a, c) => (data.indexOf(c) === data.lastIndexOf(c)) ? a.concat(c) : a, []);
}
console.log(existance([1,1,1,2]));
console.log(existance([1,1,2,3,4,5,5,6,6,6]));

javascript: how to remove duplicate arrays inside array of arrays

Input:
[[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]]
The output I want:
[[-1,-1,2],[-1,0,1]]
Any other ideas except this one?
Thanks
You won't really get around stringifying the arrays, as that's the simplest (and reasonably fast) way to compare them by value. So I'd go for
Array.from(new Set(input.map(JSON.stringify)), JSON.parse)
See also Remove Duplicates from JavaScript Array for other approaches, though most of them will require two values to be comparable by ===.
Magic
d.filter(( t={}, a=> !(t[a]=a in t) ));
I assume your input data are in array d. Explanation here.
let d = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]];
var r = d.filter((t={},a=>!(t[a]=a in t)));
console.log(JSON.stringify(r));
There's already a good utility for that, try Lodash, one of the function of it is _.uniqWith, with that function you can do the following.
<script src="/path/to/lodash.js"></script>
<script>
var aa = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]];
console.log(aa);
console.log(_.uniqWith(aa,_.isEqual));
</script>
You can create a hashMap and save values in it. This will always hold last value.
var data = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]]
var hashMap = {}
data.forEach(function(arr){
// If your subArrays can be in any order, you can use .sort to have consistant order
hashMap[arr.join("|")] = arr;
});
var result = Object.keys(hashMap).map(function(k){
return hashMap[k]
})
console.log(result)
jsfiddle
Borrowing the array comparison code from this post
// Warn if overriding existing method
if(Array.prototype.equals)
console.warn("Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there's a framework conflict or you've got double inclusions in your code.");
// attach the .equals method to Array's prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;
// compare lengths - can save a lot of time
if (this.length != array.length)
return false;
for (var i = 0, l=this.length; i < l; i++) {
// Check if we have nested arrays
if (this[i] instanceof Array && array[i] instanceof Array) {
// recurse into the nested arrays
if (!this[i].equals(array[i]))
return false;
}
else if (this[i] != array[i]) {
// Warning - two different object instances will never be equal: {x:20} != {x:20}
return false;
}
}
return true;
}
var old = [[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,-1,2],[-1,0,1],[-1,0,1]], n = [];
while(old.length) {
var arr = old.shift(), matched = false;
for(var i = 0, len = n.length; i < len; i++) {
if (arr.equals(n[i])) {
matched = true;
break;
}
}
if (!matched) {
n.push(arr);
}
}
const removeDuplicates = (arr = []) => {
const map = new Map();
arr.forEach((x) => map.set(JSON.stringify(x), x));
arr = [...map.values()];
return arr;
};
console.log(
removeDuplicates([
[1, 1, 6],
[1, 2, 5],
[1, 7],
[1, 2, 5],
[1, 7],
[2, 6],
])
);
// we can use simple JS object also to store unique elements like { "[1, 1, 6]" : [1, 1, 6] }
//resource - https://hackinbits.com/articles/how-to-iterate-a-map-in-javascript---map-part-2

javascript: remove values from an array that are in a second array

Using pure javascript, starting with an array, I would like to return and array by removing values that match any value in a second array.
I have solved this problem, but I believe with more code than is really necessary.
I am hoping for a more concise or elegant solution using only javascript.
function removeValues(arr){
array = arguments[0];
args = Array.prototype.slice.call(arguments);
len = arguments.length;
filtered = array.filter(function(n){
x = true;
for (var i = 1; i < len; i++) {
if (n == args[i]) { x = false; }
}
return x;
});
return filtered;
}
removeValues([1,2,3,1,2,3],2,3);
Should use a function that removes values from the first argument (an array) using values in one or more additional arguments.
When you're working with the filter function is not necessary to use loops because you're already in a loop. After converting the arguments into an array with [].slice.call(arguments), you could use indexOf that is responsible for returning the position of a value in an array, if a value is not exists, this returns -1, so we will take all the results that are -1
Your code could be reduced as well:
function removeValues(arr){
return arr.filter(function(val){
return [].slice.call(removeValues.arguments).slice(1).indexOf(val) === -1
})
}
console.log(removeValues([1,2,3,1,2,3],2,3))
ES6 Method: Using Rest parameters and Arrow Functions
var removeValues = (arr, ...values) => arr.filter(val => values.indexOf(val) === -1)
Try this instead...
function removeValues(){
var args = Array.prototype.slice.call(arguments).slice(1);
return arguments[0].filter(function(value) {
return args.indexOf(value) === -1;
});
}
removeValues([1, 2, 3, 1, 2, 3], 2, 3);
It does the exact same thing, but tidies it slightly.
Try like this:
var array1 = [ 1, 2, 3, 4, 5 ];
var array2 = [ 2, 3 ];
var result = array1.filter( function ( elem ) {
return array2.indexOf( elem ) === -1;
});
See example: Running code

Categories