This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 1 year ago.
I'm trying to compare two arrays.
firstArray has 451 integers in it, secondArray has 91 integers in it.
All integers that are in secondArray are also in firstArray.
I want to log out the integers from firstArray that are not in secondArray.
I tried the following :
for (let i = 0; i < firstArray.length; i++) {
for (let j = 0; j < secondArray.length; j++) {
if (firstArray[i] !== secondArray[j]) {
console.log(firstArray[i])
} } }
But it returned all 451 integers from the firstArray where I expected it to return 360 integers (firstArray - secondArray)
It's my first time posting here, hope it's clear enough ahah.
Use flags to keep track of which parts are in the set and which are not.
const arrOne = [34,2,12,4,76,7,8,9]
const arrTwo = [8,12,2]
let isInSet = false
const notInSet = []
// Expected output: 34, 4, 76, 7, 9
arrOne.forEach((el, i) => {
isInSet = false
arrTwo.forEach((curr, j) => {
if (el == curr) {
isInSet = true
}
})
if (!isInSet) {
notInSet.push(el)
}
})
console.log(notInSet)
// OR spread them out
console.log(...notInSet)
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I found myself a problem. I want to print an array from number 0 to 100.
if the number is divisible by 3, I want to print flip.
if the number is divisible by 5, I want to print flop.
for example the array should be [0,1,2,'flip',4,'flop','flip,........,'flop'].
How to do this in JS?
So far I have done this but it doesn't print the whole array.
function wow() {
var arr = []
for (let i = 0; i <= 100; i++) {
if(i!=0){
if(i%3===0){
i='flip'
arr.push(i)
}
if(i%5===0){
i='flop'
arr.push(i)
}
}
arr.push(i)
}
console.log(arr)
}
wow()
You're changing the variable i within the for loop which you shouldn't be doing. Try using a temp variable for determining what gets pushed to your array.
Also, if a number is divisible by 3 AND 5 then the latter (flop) takes precedent, is that what you expect to happen?
function wow() {
var arr = []
for (let i = 0; i <= 100; i++) {
let temp = i;
if (i != 0) {
if (i % 3 === 0) {
temp = 'flip'
}
if (i % 5 === 0) {
temp = 'flop'
}
}
arr.push(temp)
}
console.log(arr);
}
Here's a bit shorter version...
let arr = Array.from({
length: 101
}, (e, i) => i)
arr.forEach((n, i) => {
Number.isInteger(n / 3) ? arr[i] = 'flip' : null, Number.isInteger(n / 5) ? arr[i] = 'flop' : null
})
console.log(arr)
const dot = (a,b) => x => a(b(x));
const id = x => x;
function flipflop(n){
const f = (N, m) => n % N ? id : x => _ => m + x('');
return dot(f(3, 'flip'), f(5, 'flop')) (id) (n);
}
let arr = Array(101).fill(0).map((_,i)=>flipflop(i));
console.log(arr);
Written this 2sums code to get efficent O(N) Time complexity algorithm for below problem
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].
unfortunately saw value at array nums got displayed in the output ,whereas the need is to get the indices to be displayed in output
What change needs to be done below
let hashTwoSum = (array, sum) => {
let numsObj = {}
let nums = []
for(let i in array){
let addend = sum - array[i]
if (addend in numsObj){
nums.push([addend, array[i]])
}
numsObj[array[i]] = i
}
return nums
}
let array = [2,7,11,15]
console.log(hashTwoSum(array,9))
Your help is appreciated
Regards,
Carolyn
As #jriend00 said, do not use for(... in ...) loop for iterating arrays. But in your case, where you need indices, you need to use the good old for loop: for(let i = 0; i < array.length; i++). And when you save results, you need to push both indices: nums.push([numsObj[addend], i]).
Here's a complete example:
let hashTwoSum = (array, sum) => {
let numsObj = {}
let nums = []
for(let i = 0; i < array.length; i++){
let addend = sum - array[i]
if (addend in numsObj){
nums.push([numsObj[addend], i])
}
numsObj[array[i]] = i
}
return nums
}
let array = [2,7,11,15,6]
console.log(hashTwoSum(array,17))
This will output:
[ [ 0, 3 ], [ 2, 4 ] ]
because 2 + 15 and 11 + 6 are both equal 17.
This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 7 years ago.
I have this JavaScript array with length 129.
var fullnames = [Karri, Ismo, Grigori, Ahmed, Roope, Arto .....]
I would like to find how many times those names appeared in an array and store that information in an array like this:
var counter = [2, 5, 7, ..]
where Karri occured in fullnames array 2 times, Ismo occured 5 times etc. Any ideas about how to do it?
This is the best - and simple - way I can think of:
var fullnames = ["Karri", "Ismo", "Grigori", "Ahmed", "Roope", "Ahmed", "Karri", "Arto", "Ahmed"];
var counts = {};
for (var i = 0; i < fullnames.length; i++)
{
if (!counts.hasOwnProperty(fullnames[i]))
{
counts[fullnames[i]] = 1;
}
else
{
counts[fullnames[i]]++;
}
}
console.log(counts);
Original Fiddle.
Using an array to store the counts doesn't makes much sense, so I used an object instead.
I am assuming that fullnames is array of strings. If so, you can do it like so:
var occurences = { };
for (var i = 0; i < fullnames.length; i++) {
if (typeof occurences[fullnames[i]] == "undefined") {
occurences[fullnames[i]] = 1;
} else {
occurences[fullnames[i]]++;
}
}
console.log(occurences); // Prints out something like: {"Karri": 2, "Ismo": 5, ...}
var fullnames = ['Karri', 'Ismo', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori'];
var counts = [];
fullnames.forEach(function(_item) {
if(typeof counts[_item] === 'undefined') counts[_item] = 1;
else counts[_item]++;
});
var result = [];
for(i in counts) result.push(counts[i]);
console.log(result);
// outputs [3, 3, 5]
This question already has answers here:
How can I only keep items of an array that match a certain condition?
(3 answers)
Closed 6 years ago.
I'm a really beginner in javascript
I have an array containing
array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"]
And I want another array but only with words that have length > 3
array_cleaned = ["quick","brown","jumped","lazy"]
How it is currently implemented:
array_1 = ["the","quick","brown","fox","jumped","over","the","lazy","dog"]
array_clean = [];
for(var i=0; i<array_1.length; i++){
if(array_1[i].length > 3)
array_clean.push(array_1[i]);
}
document.write(array_clean)
But I'm looking for a way to actually filter it. Any ideas?
You can use filter method:
const array_1 = ["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
const new_array = array_1.filter((element) => {
return element.length > 3;
});
// OR refactor
// const new_array = array_1.filter( (element) => element.length > 3);
console.log(new_array)
// Output:
// ["quick", "brown", "jumped", "over", "lazy"]
You can filter it
var array_cleaned = array_1.filter(function(x) {
return x.length > 3;
});
If you don't want to use the filter function, this works just fine I think.
arrayClean = [];
for(int i = 0; i<array1.length; i++) {
if(array1[i].length < 3) {
arrayClean[i] = array[i];
}
}
I've seen a few generators out there but they all make a squared matrix. For example, you give it a list of three items and it'll assume the output of the length is also three. However, I'd like to specify the items and the length.
Sound like an easy problem can't believe there isn't a library available for it. Would like to avoid writing this myself if there's a tested library out there. Any suggestions would be great.
Example of what i've found
var list = 'abc';
perms = permutations(list);
//you cannot define the length
Example
var list = 'abc';
var length = 3;
perms = permutations(list,length);
console.log(perms);
/* output
a,a,a
a,b,c
a,b,a
a,c,a
c,a,a
...
*/
I would like to be able to change length and should create permutations accordingly
length = 2
a,a
a,b
b,b
b,a
length = 4
a,a,a,a
a,a,a,b
....
You can imagine the length as representing the number of slots. Each slot has N possibilities, given that N is the number of elements in your initial list. So given three values [1,2,3], you will have a total of 3 x 3 x 3 = 27 permutations.
Here's my attempt. Comments included!
var list = [1,2,3];
var getPermutations = function(list, maxLen) {
// Copy initial values as arrays
var perm = list.map(function(val) {
return [val];
});
// Our permutation generator
var generate = function(perm, maxLen, currLen) {
// Reached desired length
if (currLen === maxLen) {
return perm;
}
// For each existing permutation
for (var i = 0, len = perm.length; i < len; i++) {
var currPerm = perm.shift();
// Create new permutation
for (var k = 0; k < list.length; k++) {
perm.push(currPerm.concat(list[k]));
}
}
// Recurse
return generate(perm, maxLen, currLen + 1);
};
// Start with size 1 because of initial values
return generate(perm, maxLen, 1);
};
var res = getPermutations(list, 3);
console.log(res);
console.log(res.length); // 27
fiddle
If you're looking for an answer based on performance, you can use the length of the array as a numerical base, and access the elements in the array based on this base, essentially replacing actual values from the base with the values in your array, and accessing each of the values in order, using a counter:
const getCombos = (arr, len) => {
const base = arr.length
const counter = Array(len).fill(base === 1 ? arr[0] : 0)
if (base === 1) return [counter]
const combos = []
const increment = i => {
if (counter[i] === base - 1) {
counter[i] = 0
increment(i - 1)
} else {
counter[i]++
}
}
for (let i = base ** len; i--;) {
const combo = []
for (let j = 0; j < counter.length; j++) {
combo.push(arr[counter[j]])
}
combos.push(combo)
increment(counter.length - 1)
}
return combos
}
const combos = getCombos([1, 2, 3], 3)
console.log(combos)
For smaller use cases, like the example above, performance shouldn't be an issue, but if you were to increase the size of the given array from 3 to 10, and the length from 3 to 5, you have already moved from 27 (33) combinations to 100,000 (105), you can see the performance difference here:
I wrote a little library that uses generators to give you permutations with custom items and number of elements. https://github.com/acarl005/generatorics
const G = require('generatorics')
for (let perm of G.permutation(['a', 'b', 'c'], 2)) {
console.log(perm);
}
// [ 'a', 'b' ]
// [ 'a', 'c' ]
// [ 'b', 'a' ]
// [ 'b', 'c' ]
// [ 'c', 'a' ]
// [ 'c', 'b' ]