Finding the sum of a nested array - javascript

I tried finding the sum of all numbers of a nested array, but I don't get it to work correctly. This is what I tried:
function arraySum(i) {
sum = 0;
for (a = 0; a < i.length; a++) {
if (typeof i[a] == 'number') {
sum += i[a];
} else if (i[a] instanceof Array) {
sum += arraySum(i[a]);
}
}
return sum;
}
When you try it out with the array [[1,2,3],4,5], it gets 6 as the answer, instead of 15.
Does somebody know where there is a mistake in it?

The problem with your code is that the sum and a variables are global, instead of local. Because of this you get an infinite loop (a from the first entry in the function is reset by the second entry, so the same elements are processed again).
Fix it by adding var to where sum and a are declared to make them local to the function:
function arraySum(i) {
var sum=0; // missing var added
for(var a=0;a<i.length;a++){ // missing var added
if(typeof i[a]=="number"){
sum+=i[a];
}else if(i[a] instanceof Array){
sum+=arraySum(i[a]);
}
}
return sum;
}
Demo: http://jsbin.com/eGaFOLA/2/edit

I know it's late, but they say "is never late" :)
const sumNestedArray = arr => arr.flat(Infinity).reduce((a,b)=> a+b, 0)
const sumNestedArray = arr => arr.flat(Infinity).reduce((a,b)=> a+b, 0)
console.log(sumNestedArray([1,[2], [2, 3, [4]]]))
sumNestedArray([1,[2], [2, 3, [4]]])

For 2018 this solution is clean and functional:
let arr = [[ 1, 2, 3], 4, 5]
arr.flat().reduce((d, i) => d + i)
Documentation for flat and reduce.

Recurse, for example
function arraySum(x) {
var sum = 0, i;
if (typeof x === 'number')
return x;
else if (x instanceof Array)
for (i = 0; i < x.length; ++i)
sum += arraySum(x[i]);
return sum;
}
arraySum([[1,2,3],4,5]); // 15
I didn't optimise this so that it's clear, you may want some more logic before recursion.
The reason yours isn't working is because you need to var both sum and a.

You're missing two var in there. You've implicitly declared sum and a at window scope:
function arraySum(i) {
**var** sum=0;
for(**var** a=0;a<i.length;a++){
if(typeof i[a]=="number"){
sum+=i[a];
}else if(i[a] instanceof Array){
sum+=arraySum(i[a]);
}
}
return sum;
}

First of all why you use 'i' as input to function? we using 'i' to denote running index..
Regarding your question,you want 'a' to be local in your loop so instead of "for(a=0;..." instead write "for(var a=0;"
<html>
<body>
<script>
function NestedArraySummation(arr)
{
var sum=0;
for(var i=0;i<arr.length;i++)
{
if(typeof arr[i]=="number")
sum=sum+arr[i];
else if(arr[i] instanceof Array)
sum=sum+NestedArraySummation(arr[i]);
}
return sum;
}
var MyArray=[1,[2,3],4,10,[1,2]];
var Sum=NestedArraySummation(MyArray);
document.write(Sum);
</script>
</body>
</html>

This can be done with lodash _.flattenDeep and _.sum:
const arr = [[1, 2, 3], 4, 5];
arraySum(arr);
function arraySum(arr) {
var arrFlattens = _.flattenDeep(arr);
// => [1, 2, 3, 4, 5]
console.log(_.sum(arrFlattens));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Here you go:
(My assumption is that you want to parse strings, e.g., '13', into numbers in order include them in the sum. If not, just change isNumber to typeof val === 'number'.
function arraySum(arr) {
let sum = 0;
while (arr.length) {
const val = arr.pop();
const isArray = typeof val === 'object' && val.length !== undefined;
const isNumber = !isArray && !isNaN(sum + parseFloat(val));
if (isArray && val.length) {
sum += arraySum(val);
}
else if (isNumber) {
sum += parseFloat(val);
}
}
return sum;
}
console.log(arraySum([])); //0
console.log(arraySum([1, 1, 1, [3, 4, [8]], [4]])); //22
console.log(arraySum([1, 1, [], {}, 'l', 1, [3, 4, [8]], [4]])); //22

This was posted long ago but it might help others. I did the following and it seems to be working just fine
function countArray (array) {
//iterate through the array
for(let i = 0;i < array.length; i++){
//check if element of array is an array, and if it is, run method flat() to the whole array.
if(Array.isArray(array[i])){
array = array.flat()
}
}
//return the sum of the elements of the array
return array.reduce((a,b) => a + b);
}

from __builtin__ import int
def nestedLists(mylist):
sum = 0
if checkIfAllInt(mylist):
result = addList(mylist)
return result
else:
for value in mylist:
sum = sum + nestedLists(value)
return sum
def addList(listdata):
if(type(listdata) is int):
return listdata
else:
return sum(listdata)
def checkIfAllInt(listdata):
check = True
if(type(listdata) is int):
return check
else:
for value in listdata:
if(not type(value) is int):
check = False
return check
return check
print nestedLists([1,[2,3,[4,5,[6,7]]]])

Related

Is there a way to return a conditional object value and key?

I am new and learning programming.
I wondered if there is a way to get a specific value + key or (in this case) key from an object if it passes a condition.
function miti (a){
let obj = {};
let num;
for(let i =0; i < a.length; i++){
num = a[i]
if(obj[num] === undefined){
obj[num]= 1
} else {
obj[num] ++
}
}
//Now I have created an object that records the frequancy of each presented number.
if(Object.values(obj) === 1){
return
}
}
console.log(miti([1,2,1,3,4,3,4,5))
From the above code, I would like to extract a lonely number with no pairs, I built an object that records each frequency from a given array.
Please be a little descriptive since I am a newbie.
Object.values(obj) === 1 doesn't make any sense because Object.values returns an array, which definitely won't be equal to a number.
Iterate through the entries of the object (the key-value pairs) and return the first entry for which the value is 1.
function miti(a) {
let obj = {};
let num;
for (let i = 0; i < a.length; i++) {
num = a[i]
if (obj[num] === undefined) {
obj[num] = 1
} else {
obj[num]++
}
}
for (const entry of Object.entries(obj)) {
if (entry[1] === 1) {
return entry[0];
// or return entry, if you want the whole entry and not just the key
}
}
}
console.log(miti([1, 2, 1, 3, 4, 3, 4, 5]))
Or .find the entry matching the condition and return it.
function miti(a) {
let obj = {};
let num;
for (let i = 0; i < a.length; i++) {
num = a[i]
if (obj[num] === undefined) {
obj[num] = 1
} else {
obj[num]++
}
}
return Object.entries(obj)
.find(entry => entry[1] === 1)
[0];
}
console.log(miti([1, 2, 1, 3, 4, 3, 4, 5]))
Or, using the Array methods .forEach() and .find() in combination with Object.keys() you can do it like that:
function firstUniqueValue(a) {
let obj = {};
a.forEach(k=>obj[k]=(obj[k]||0)+1);
return Object.keys(obj).find(k=>obj[k]==1);
}
console.log(firstUniqueValue([1, 2, 1, 3, 4, 3, 4, 5]))

Javascript function that counts how many numbers are in the array (the array can contain other arrays)

How can I write a function that, received an array a already given from the program that can contain numbers, boolean and even other arrays, counts how many numbers are present in a?
Here's my code that doesn't work (it gives everytime 0 whatever the array contains):
function test(a) {
var sum = 0
for (i=0; i<a.length; i++){
if (typeof a[i]==Number)
sum++
}
return sum
}
Thanks.
you can try this:
const array = ["Hi", true, 10, "Car", 20, 50, 1500, false];
const flatedArray = array.flat(Infinity);
const count = flatedArray.filter(x => typeof x == 'number').length;
console.log(count) // 4
or change your code:
function test(a) {
const flatedArray = a.flat(Infinity);
let sum = 0
for (i = 0; i < flatedArray.length; i++) {
if (typeof a[i] == 'number') {
sum++
}
}
return sum
}
const array = ["Hi", true, 10, "Car", 20, 50, 1500, false];
console.log(test(array)) // 4
or change your function:
function test(a) {
const flat = a.flat(Infinity);
return a.filter(x => typeof x == 'number').length;
}
const array = ["Hi", true, 10, "Car", 20, 50, 1500, false];
console.log(test(array)) // 4
You have some issues:
typeof <operand> returns a string and not an object, you should be checking against a string typeof a[i] === "number".
You should be using var/let before i in your for loop so that i doesn't become a global variable and instead remains scoped to your function (if you use var) or your for loop (if you use let). Having variables accidentally added to the global scope can easily lead to bugs for code that runs after you call your test() function.
As you want to count the frequency of numbers in both your array and nested arrays, you can use recursion. The idea is to call your test() function again inside of test() when you encounter an array:
function test(a) {
let sum = 0;
for (let i = 0; i < a.length; i++) {
if (typeof a[i] === "number")
sum++
else if(Array.isArray(a[i]))
sum += test(a[i]); // sum the numbers within the `a[i]` array
}
return sum;
}
console.log(test([1,4, [2, 3, true], ["foo",0], 5, [123, [3.14, {a: 1}]]])); // 8
The other option is to get JS to handle the recursion for you, which can be done with the help of the .flat() method. By using .flat(Infinity) you can first flatten your array (ie: remove the inner arrays of any level), and then loop over it:
function test(a) {
let sum = 0;
let flat = a.flat(Infinity);
for (let i = 0; i < flat.length; i++) {
if (typeof flat[i] === "number")
sum++;
}
return sum;
}
console.log(test([1,4, [2, 3, true], ["foo",0], 5, [123, [3.14, {a: 1}]]])); // 8

Sum of elements in array using recursion even if they are string

Have to create a function that return the sum of the element in the array but if the array is
["a","b","c"] // output : abc
So far I have
function calculateSumRecursion(array) {
//your code
if (array.length === 0 ) {
return 0
}
return array[0] + calculateSumRecursion(array.slice(1))
}
I found out how to calculate the sum of all numbers using recursion but when it's an array of string like
array = ["a","b","c"]
it returns me
// abc0
because of the if statement.. is there any way to say
if (array.length === 0) return nothing instead of a 0 (that work only when it's an array of number?)
You just need to return the only value in the array when the length is 1, rather than waiting until you get a length of 0. That way you are always summing compatible types (numbers or strings). Note that you still need a test for a 0 array length in case the function gets called with an empty array. In this case you need to choose what to return; as requested, it is 0.
function calculateSumRecursion(array) {
if (array.length === 0) {
return 0;
}
if (array.length === 1) {
return array[0];
}
return array[0] + calculateSumRecursion(array.slice(1))
}
console.log(calculateSumRecursion([1, 2, 3, 4, 5]));
console.log(calculateSumRecursion(['a', 'b', 'c']));
console.log(calculateSumRecursion([]));
let arr = [1,2,3,4,5] // output : abc
let sum = calculateSumRecursion(arr);
function calculateSumRecursion (arr) {
return arr.length ? arr.pop() + calculateSumRecursion(arr) : 0;
}
Slice version
let arr = [1,2,3,4,5] // output : abc
let sum = calculateSumRecursion(arr);
function calculateSumRecursion (arr) {
return arr.length ? arr[0] + calculateSumRecursion(arr.slice(1)) : 0;
}
Change return 0 to return "" which will add an empty string to the sum.
You have returned 0 when the array is empty.
Now, you are doing string operations so it is needed to return empty value (not zero) so it will be affordable to return "".
function calculateSumRecursion(array) {
return array.length === 0 ? "" : array[0] + calculateSumRecursion(array.slice(1));
}
There's a way easier way to do this:
function calculateSumRecursion(array) {
var out = array[0];
for (let i = 1; i < array.length; i++) {
out = out + array[i];
}
return out;
}
Return empty string on recursion base case. Just replace your return 0 to return ''.
const array = ['a', 'b', 'c'];
function calculateSumRecursion(array) {
if (array.length === 0) {
return '';
}
return array[0] + calculateSumRecursion(array.slice(1));
}
console.log(calculateSumRecursion(array));
If you are want to work with number also then check array length for zero as well as one.
const array = ['a', 'b', 'c', 'e'];
const array2 = [];
const array3 = [1, 2, 3];
function calculateSumRecursion(array) {
const rec =
array.length === 1
? array[0]
: array.length >= 1 && array[0] + calculateSumRecursion(array.slice(1));
return array.length === 0 ? 0 : rec;
}
console.log(calculateSumRecursion(array));
console.log(calculateSumRecursion(array2));
console.log(calculateSumRecursion(array3));

Remove Strings, Keep Numbers In Array With JavaScript

Other articles talk about removing strings from an array based on a search term.
But I'm trying to indentify which elements are strings and which elements are numbers in an array, and then remove all strings to return a new array.
function filter_list(l) {
let newArray = [];
for (let i = 0; i < l.length; i ++) {
if (i !== "^[a-zA-Z0-9_.-]*$") {
newArray = newArray + i;
}
}
return newArray;
}
This is returning 0123.
Why is it not returning an array?
Why is if (i !== "^[a-zA-Z0-9_.-]*$") not working? How else can I check for when an element is a string (something in quotes) within the array?
https://www.codewars.com/kata/list-filtering/train/javascript
Thanks
You can is typeof keyword. and filter(). I have tested the code its passing all tests in codewars.
Using ES6 Arrow Function
function filter_list(l) {
return l.filter(x => typeof x === "number");
}
console.log(filter_list([1,2,'a','b']))
Without Arrow Function
function filter_list(l) {
return l.filter(function(x){
return typeof x === "number"
});
}
console.log(filter_list([1,2,'a','b']))
Using Simple Loops
function filter_list(l) {
let newArr = [];
for(let i = 0;i<l.length;i++){
if(typeof l[i] === "number") newArr.push(l[i]);
}
return newArr
}
console.log(filter_list([1,2,'a','b']))
Regex is not good way to parse such table. Try isNaN
console.log(
[1,2,3,4,5, 'a', 'b', 1, 3].filter(item => !isNaN(item) ? item : '')
)
If you want less hacky way try
function filter_list(l) {
// l is very bad name, because look similar to i
let newArray = [];
for (let i = 0; i < l.length; i ++) {
!isNaN(l[i]) ? newArray.push(l[i]) : ''
}
return newArray;
}
or even
for (let i = 0; i < l.length; i ++) {
!isNaN(l[i]) ? newArray[i] = l[i] : ''
}
Hovewer, this task can be done with regexes, but I cannot recommend this solution.
[1,2,3,4,5, 'a', 'b', 1, 3].join(' ').replace(/\D/gm, '').split('')
var numberArray: any[];
numberArray.filter(Number)
Using this you can filter only numbers in an array and then can performe what you want.
function filter_list(l) {
return l.filter(x => typeof x === "number");
}
console.log(filter_list([1,2,'a','b']))
I worked out a simple answer that will work as well using the same logic required to solve your problem. I used it on an example where you have an array of temperature values, and you want to remove all the values which are strings from the existing array, then populate the new empty array.You can use typeof operator to identify the type of value in the temperatures array at position i which is the index of that array element. If the type of that value is not a string then push the value of the temperatures array at the current index position to the new array.
const temperatures = [3, -2, -6, -1, 'error', 9, 13, 17, 15, 14, 9, 5];
const cleanTemperatures = [];
for (let i = 0; i < temperatures.length; i++) {
if (typeof temperatures[i] !== 'string') {
cleanTemperatures.push(temperatures[i]);
}
}

Check if every element in one array is in a second array

I have two arrays and I want to check if every element in arr2 is in arr1. If the value of an element is repeated in arr2, it needs to be in arr1 an equal number of times. What's the best way of doing this?
arr1 = [1, 2, 3, 4]
arr2 = [1, 2]
checkSuperbag(arr1, arr2)
> true //both 1 and 2 are in arr1
arr1 = [1, 2, 3, 4]
arr2 = [1, 2, 5]
checkSuperbag(arr1, arr2)
> false //5 is not in arr1
arr1 = [1, 2, 3]
arr2 = [1, 2, 3, 3]
checkSuperbag(arr1, arr2)
> false //3 is not in arr1 twice
Do you have to support crummy browsers? If not, the every function should make this easy.
If arr1 is a superset of arr2, then each member in arr2 must be present in arr1
var isSuperset = arr2.every(function(val) { return arr1.indexOf(val) >= 0; });
Here's a fiddle
EDIT
So you're defining superset such that for each element in arr2, it occurs in arr1 the same number of times? I think filter will help you do that (grab the shim from the preceding MDN link to support older browsers):
var isSuperset = arr2.every(function (val) {
var numIn1 = arr1.filter(function(el) { return el === val; }).length;
var numIn2 = arr2.filter(function(el) { return el === val; }).length;
return numIn1 === numIn2;
});
Updated Fiddle
END EDIT
If you do want to support older browsers, the MDN link above has a shim you can add, which I reproduce here for your convenience:
if (!Array.prototype.every)
{
Array.prototype.every = function(fun /*, thisp */)
{
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in t && !fun.call(thisp, t[i], i, t))
return false;
}
return true;
};
}
EDIT
Note that this will be an O(N2) algorithm, so avoid running it on large arrays.
One option is to sort the two arrays, then traverse both, comparing elements. If an element in the sub-bag candidate is not found in the super-bag, the former is not a sub-bag. Sorting is generally O(n*log(n)) and the comparison is O(max(s,t)), where s and t are the array sizes, for a total time complexity of O(m*log(m)), where m=max(s,t).
function superbag(sup, sub) {
sup.sort();
sub.sort();
var i, j;
for (i=0,j=0; i<sup.length && j<sub.length;) {
if (sup[i] < sub[j]) {
++i;
} else if (sup[i] == sub[j]) {
++i; ++j;
} else {
// sub[j] not in sup, so sub not subbag
return false;
}
}
// make sure there are no elements left in sub
return j == sub.length;
}
If the elements in the actual code are integers, you can use a special-purpose integer sorting algorithm (such as radix sort) for an overall O(max(s,t)) time complexity, though if the bags are small, the built-in Array.sort will likely run faster than a custom integer sort.
A solution with potentially lesser time-complexity is to create a bag type. Integer bags are particularly easy. Flip the existing arrays for the bags: create an object or an array with the integers as keys and a repeat count for values. Using an array won't waste space by creating as arrays are sparse in Javascript. You can use bag operations for sub-bag or super-bag checks. For example, subtract the super from the sub candidate and test if the result non-empty. Alternatively, the contains operation should be O(1) (or possibly O(log(n))), so looping over the sub-bag candidate and testing if the super-bag containment exceeds the sub-bag's containment for each sub-bag element should be O(n) or O(n*log(n)).
The following is untested. Implementation of isInt left as an exercise.
function IntBag(from) {
if (from instanceof IntBag) {
return from.clone();
} else if (from instanceof Array) {
for (var i=0; i < from.length) {
this.add(from[i]);
}
} else if (from) {
for (p in from) {
/* don't test from.hasOwnProperty(p); all that matters
is that p and from[p] are ints
*/
if (isInt(p) && isInt(from[p])) {
this.add(p, from[p]);
}
}
}
}
IntBag.prototype=[];
IntBag.prototype.size=0;
IntBag.prototype.clone = function() {
var clone = new IntBag();
this.each(function(i, count) {
clone.add(i, count);
});
return clone;
};
IntBag.prototype.contains = function(i) {
if (i in this) {
return this[i];
}
return 0;
};
IntBag.prototype.add = function(i, count) {
if (!count) {
count = 1;
}
if (i in this) {
this[i] += count;
} else {
this[i] = count;
}
this.size += count;
};
IntBag.prototype.remove = function(i, count) {
if (! i in this) {
return;
}
if (!count) {
count = 1;
}
this[i] -= count;
if (this[i] > 0) {
// element is still in bag
this.size -= count;
} else {
// remove element entirely
this.size -= count + this[i];
delete this[i];
}
};
IntBag.prototype.each = function(f) {
var i;
foreach (i in this) {
f(i, this[i]);
}
};
IntBag.prototype.find = function(p) {
var result = [];
var i;
foreach (i in this.elements) {
if (p(i, this[i])) {
return i;
}
}
return null;
};
IntBag.prototype.sub = function(other) {
other.each(function(i, count) {
this.remove(i, count);
});
return this;
};
IntBag.prototype.union = function(other) {
var union = this.clone();
other.each(function(i, count) {
if (union.contains(i) < count) {
union.add(i, count - union.contains(i));
}
});
return union;
};
IntBag.prototype.intersect = function(other) {
var intersection = new IntBag();
this.each(function (i, count) {
if (other.contains(i)) {
intersection.add(i, Math.min(count, other.contains(i)));
}
});
return intersection;
};
IntBag.prototype.diff = function(other) {
var mine = this.clone();
mine.sub(other);
var others = other.clone();
others.sub(this);
mine.union(others);
return mine;
};
IntBag.prototype.subbag = function(super) {
return this.size <= super.size
&& null !== this.find(
function (i, count) {
return super.contains(i) < this.contains(i);
}));
};
See also "comparing javascript arrays" for an example implementation of a set of objects, should you ever wish to disallow repetition of elements.
No one has posted a recursive function yet and those are always fun. Call it like arr1.containsArray( arr2 ).
Demo: http://jsfiddle.net/ThinkingStiff/X9jed/
Array.prototype.containsArray = function ( array /*, index, last*/ ) {
if( arguments[1] ) {
var index = arguments[1], last = arguments[2];
} else {
var index = 0, last = 0; this.sort(); array.sort();
};
return index == array.length
|| ( last = this.indexOf( array[index], last ) ) > -1
&& this.containsArray( array, ++index, ++last );
};
Using objects (read: hash tables) in stead of sorting should reduce the amortized complexity to O(m+n):
function bagContains(arr1, arr2) {
var o = {}
var result = true;
// Count all the objects in container
for(var i=0; i < arr1.length; i++) {
if(!o[arr1[i]]) {
o[arr1[i]] = 0;
}
o[arr1[i]]++;
}
// Subtract all the objects in containee
// And exit early if possible
for(var i=0; i < arr2.length; i++) {
if(!o[arr2[i]]) {
o[arr2[i]] = 0;
}
if(--o[arr2[i]] < 0) {
result = false;
break;
}
}
return result;
}
console.log(bagContains([1, 2, 3, 4], [1, 3]));
console.log(bagContains([1, 2, 3, 4], [1, 3, 3]));
console.log(bagContains([1, 2, 3, 4], [1, 3, 7]));
Which yields true, false, false.
Found this on github lodash library. This function use built in functions to solve the problem. .includes() , .indexOf() and .every()
var array1 = ['A', 'B', 'C', 'D', 'E'];
var array2 = ['B', 'C', 'E'];
var array3 = ['B', 'C', 'Z'];
var array4 = [];
function arrayContainsArray (superset, subset) {
if (0 === subset.length) {
return false;
}
return subset.every(function (value) {
return (superset.includes(value));
});
}
function arrayContainsArray1 (superset, subset) {
if (0 === subset.length) {
return false;
}
return subset.every(function (value) {
return (superset.indexOf(value) >= 0);
});
}
console.log(arrayContainsArray(array1,array2)); //true
console.log(arrayContainsArray(array1,array3)); //false
console.log(arrayContainsArray(array1,array4)); //false
console.log(arrayContainsArray1(array1,array2)); //true
console.log(arrayContainsArray1(array1,array3)); //false
console.log(arrayContainsArray1(array1,array4)); //false
If arr2 is subset of arr1, then Length of set(arr1 + arr2) == Length of set(arr1)
var arr1 = [1, 'a', 2, 'b', 3];
var arr2 = [1, 2, 3];
Array.from(new Set(arr1)).length == Array.from(new Set(arr1.concat(arr2))).length
Here is my solution:
Array.prototype.containsIds = function (arr_ids) {
var status = true;
var current_arr = this;
arr_ids.forEach(function(id) {
if(!current_arr.includes(parseInt(id))){
status = false;
return false; // exit forEach
}
});
return status;
};
// Examples
[1,2,3].containsIds([1]); // true
[1,2,3].containsIds([2,3]); // true
[1,2,3].containsIds([3,4]); // false
As for another approach you may do as follows;
function checkIn(a,b){
return b.every(function(e){
return e === this.splice(this.indexOf(e),1)[0];
}, a.slice()); // a.slice() is the "this" in the every method
}
var arr1 = [1, 2, 3, 4],
arr2 = [1, 2],
arr3 = [1,2,3,3];
console.log(checkIn(arr1,arr2));
console.log(checkIn(arr1,arr3));
Quick solution here take two arrays if b is longer than it can't be a super set so return false. Then loop through b to see if a contains the element. If so delete it from a and move on if not return false. Worse case scenario is if b is a subset then time will b.length.
function isSuper(a,b){
var l=b.length,i=0,c;
if(l>a.length){return false}
else{
for(i;i<l;i++){
c=a.indexOf(b[i]);
if(c>-1){
a.splice(c,1);
}
else{return false}
}
return true;
}
}
This assumes that inputs will not always be in order and if a is 1,2,3 and b is 3,2,1 it will still return true.
Yet another simple solution is the following:
let a = [1,2,'a',3,'b',4,5]
let b = [1,2,4]
console.log(b.every((i) => a.includes(i)))
Hope it helps

Categories

Resources