Why i can't remove other array element in javascript? - javascript

I am working with arrays now but if I remove the second element that I choose the first one that I removed keeps returning to its spot. How can I solve this?
Here is the Code:
const fruits = ['Apple', 'Banana','Lemon', 'Guava'];
const removeItem = (arr, item) => {
let newArray = [...arr];
const index = newArray.findIndex((element)=>element===item)
if(index !== -1){
newArray.splice(index, 1)
return newArray
}
}
console.log(removeItem(fruits, 'Guava'))
console.log(removeItem(fruits, 'Lemon'))
Output:
(3) ['Apple', 'Banana', 'Lemon'] //I removed Guava
(3) ['Apple', 'Banana', 'Guava'] //I removed Lemon

Your original array is a const and cannot be updated. So it is using all original values. Here is a working version that removes from the original array.
let fruits = ['Apple', 'Banana','Lemon', 'Guava'];
const removeItem = (arr, item) => {
let newArray = [...arr];
const index = newArray.findIndex((element)=>element===item)
if(index !== -1){
newArray.splice(index, 1)
fruits = newArray;
return newArray
}
}
console.log(removeItem(fruits, 'Guava'))
console.log(removeItem(fruits, 'Lemon'))

Keywords to think about: pop push remove index placeholder
I don't understand what you are trying to achieve.
Well, I never tried Guava.

Related

Unable to push elements in a new array in javascript

I am writing a very easy function where I am checking the even numbers from an array of integer and adding those even numbers into the new array.
But after getting the even numbers from first array when I am trying to push into second array its showing undefined.
const arr = [1,2,3,4,5,6];
const newArr = [];
const loop = () => {
for (var item of array) {
if (item % 2 == 0) {
console.log(item);
newArr.push(item);
}
}
};
console.log(loop());
Output
2
4
6
undefined
Why new array is showing undefined.
You can do it simply with forEach.
const arr = [1,2,3,4,5,6];
const newArr = [];
arr.forEach(item => {
if (item % 2 == 0) {
newArr.push(item);
}
})
console.log(newArr);
either return the newArray or execute the loop method and print the new Array.
The reason why you get undefined is because loop is currently a void operator and returning nothing. so if you want the loop method to return the array then the second code sample I showed is the better solution. if you just want to print the array then the first one does the trick.
const arr = [1,2,3,4,5,6];
const newArr = [];
arr.forEach(item => {
if (item % 2 == 0) {
newArr.push(item);
}
})
console.log(newArr);
or
const arr = [1,2,3,4,5,6];
const loop = () => {
const newArr = [];
for (var item of arr) {
if (item % 2 == 0) {
console.log(item);
newArr.push(item);
}
}
return newArr
};
console.log(loop());
both will work.

A function that returns an array which is the intersection of two other arrays

function arraysCommon(array1, array2) {
return array1.filter(x => array2.includes(x));
}
This function does not work the way I want it to.
For instance given array1 = [1,2,3,2,1] and array2 = [5,4,3,2,1]
it returns [1,2,3,2,1], since the elements 1,2,3 are seen in both arrays.
But I want it to return [1,2,3] in that order since 1,2,3 are seen only once in array2 and are treated as seperate entities.
So pretty much the functionality should be that
Each element in the first array can map to at most one element in the second array.
Duplicated elements in each array are treated as separate entities.
the first array determines the order
I have attempted to loop through the arrays and check and compare the number of duplicates in each array but I can't seem to get the logic working correctly. Is there a different way to approach this?
I've attached an image of two Venn diagrams that might clarify the difference
Unfortunately, it gets more complicated because you need to know what numbers you have already added. In this case you need a temporary array to hold the result. We also need to track if a number exists in the array two times.
Try this:
function arraysCommon(array1, array2) {
//Copy array2 by duplicating and spreading the elements into another array.
var copyArray2 = [...array2];
//Temperary Array
var temp = [];
for (let x of array1) {
//Check if the element is in the first array and not already added to the temp array
if (copyArray2.includes(x)) {
temp.push(x);
//Remove item from copy array2 so it cannot be used anymore
copyArray2.splice(copyArray2.indexOf(x), 1);
}
}
//Return the temp array
return temp;
}
console.log(arraysCommon([1,2,3,2,1], [5,4,3,2,1]))
console.log(arraysCommon([1,2,3,2,1], [2,2,3,3,4]))
With sorting and counting this should be possible. Since you are incrementing when you find similar characters, this should be okay:
const array1= [1,4,1,1,5,9,2,7];
const array2 = [1,8,2,5,1]
const array3 = [1,2,3,2,1];
const array4 = [5,4,3,2,1,2]
const array5 = [1,2,3,2,1];
const array6 = [2,2,3,3,4]
function arraysCommon(array1, array2) {
const ans = [];
array1.sort();
array2.sort();
let j = 0;
let i = 0;
while(i<array1.length && j<array2.length){
if(array1[i] === array2[j]){
ans.push(array1[i]);
i++;
j++;
}
else if(array2[i] > array1[j]){
i++;
}
else{
j++;
}
}
console.log(ans);
}
arraysCommon(array1,array2);
arraysCommon(array3,array4);
arraysCommon(array5,array6);
this should work as you wanted!
// test 1
const array1 = [1,4,1,1,5,9,2,7];
const array2 = [1,8,2,5,1];
// test 2
const array3 = [1,2,3,2,1];
const array4 = [5,4,3,2,1];
const mapper = (array1, array2) => {
var obj = {};
array1.forEach((x, indexX) => {
array2.forEach((y, indexY) => {
if (x == y) {
if (!Object.values(obj).includes(indexX) && !obj.hasOwnProperty(indexY)) {
obj[indexY] = indexX;
return;
}
}
})
})
return Object.values(obj).sort().map(values => array1[values]);
}
console.log(mapper(array1, array2));
console.log(mapper(array3, array4));
I hope this helps. Cheers.
You can instance a new Set, wich brings only unique values and than retorn a array from this set.
Something like this:
function arraysCommon(array1, array2) {
const filtered = array1.filter(x => array2.includes(x));
const uniqueValues = new Set(filtered)
return Array.from(uniqueValues)
}

How to convert array to array of objects?

I have
let array = ['mango', 'mango_shake','banana', 'banana_shake', 'cherry', 'cherry_shake', 'Strawberry', 'Strawberry_shake', ...n];
What i want to do is:
let target = [{'fruit': 'mango', 'drink': 'mango_shake'},
{'fruit': 'banana', 'drink': 'banana_shake'}, ...n];
How can i do it?
You can simply loop through array and create an array of object like this
let array = ['mango', 'mango_shake', 'banana', 'banana_shake', 'cherry', 'cherry_shake', 'Strawberry', 'Strawberry_shake'];
var res = [];
for (var i = 0; i < array.length; i = i + 2) {
var ob = {};
ob.fruit = array[i];
ob.drink = array[i + 1];
res.push(ob);
}
console.log(res);
Note: This answer assumes the fruit and its corresponding drink are always right beside each other in the array. This will give wrong answers if items are out of order.
Just iterate over your original array until it is empty and take out pairs and map them to objects:
const result = [];
while(array.length)
result.push((([fruit, drink]) => ({fruit, drink}))(array.splice(0, 2));
(In case this is your homework: i think it will be harder to explain to your teacher how it works instead of just trying it on your own :))
You can iterate over the array to combine every other item
let target = {};
array.forEach( (curr, indx, arr) => {
if (indx %2 == 1) {
target[arr[indx-1]] = curr
}
});

javascript sort by index and then random?

I'm using lodash to sortBy index, but among the items with the same index the sorting always comes out to be the same. How do I make sure that the ordering is random if the index are identical?
This is what I have currently:
chosen = _.sortBy(chosen, function(v) {
return v.index;
});
vanillJS/ES6 one-liner:
var arr = [{index:5,v:1},{index:3,v:3},{index:3,v:6},{index:1,v:3},{index:3,v:7}]
arr = arr.sort((i1,i2)=>i1.index==i2.index?Math.random()-0.5:i1.index-i2.index)
console.log(arr)
EDIT: not-one-liner
var arr = [{index:5,v:1},{index:3,v:3},{index:3,v:6},{index:1,v:3},{index:3,v:7}]
arr = arr.sort(function(i1,i2){
if (i1.index == i2.index) return Math.random()-0.5;
else return i1.index-i2.index;
})
console.log(arr)

Word Frequency Count, fix a bug with standard property

I'm trying to build a javascript function which would count the number of occurrences of each word in an input array.
Example :
Input
a=["a","booster","booster","constructor","adam","adam","adam","adam"]
Output:
"a":1
"booster":2
"constructor":1
"adam":4
Output should be dict-alike.
I'm new to javascript and I tried to use a dict. But objects have a property called "constructor", so cnt["constructor"] seems not to work.
Here is my code and the result:
var cnt={};
console.log("constructor");
for(var i=0;i<a.length;++i)
{
if(! (a[i] in cnt))
cnt[a[i]]=0;
else
cnt[a[i]]+=1;
}
for(var item in cnt)
console.log(item+":"+cnt[item]);
Result:
You can see that 1 is added to constructor of cnt as a string.
function count(arr){
return arr.reduce(function(m,e){
m[e] = (+m[e]||0)+1; return m
},{});
}
The idea behind are
the use of reduce for elegance
the conversion of m[e] to a number using +m[e] to avoid the constructor (or toString) problem
Demonstration
var arr = ['apple', 'orange', 'grape', 'apple'];
var initialValue = {};
var result = arr.reduce(function(accumulator, curr, idx, arr) {
if (Object.hasOwnProperty.call(accumulator, curr)) { // does current exist as key on initialValue object?
accumulator[curr]++;
} else { // no key for current on initialValue object
accumulator[curr] = 1;
}
return accumulator;
}, initialValue);
console.log(result);
You can also create an array just by initializing [] as the initial accumulator.
var fruits = ['apple', 'orange', 'grape', 'apple'].reduce((countFruits,currentFruit)=>{
if(typeof countFruits[currentFruit]!=="undefined"){
countFruits[currentFruit] = countFruits[currentFruit]+1
return countFruits
}
countFruits[currentFruit] = 1
return countFruits
},[])
console.log(fruits)

Categories