Unable to push elements in a new array in javascript - 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.

Related

How do I remove multiple elements from an array?

I want to write a function that passes an array and an optional number of values to be removed from the array as parameters. My function works when there is only 1 value, but fails when there is multiple values.
const removeFromArray = function (arr, ...theArgs) {
for (let i = 0; i < arr.length; i++) {
if (theArgs.includes(arr[i])) {
arr.splice(i, 1);
}
}
return arr;
};
You can use the filter method for that:
const removeFromArray = function (arr, ...theArgs) {
return arr.filter( val => !theArgs.includes(val) )
};
const list = [1,2,3];
const newList = removeFromArray(list, 2,3);
console.log(newList);
And a more terse version:
const removeFromArray = (arr, ...args)=> arr.filter( val => !args.includes(val) )
Tip: try to avoid mutating the original array and work on or return a copy during these operations.
The issue is with your indexing, you are finding the element using the index of arr, and deleting in the array, which is probably causing issue with indexing in loop.
Modify your code as follows
const removeFromArray = function (arr, ...theArgs) {
for (let i = 0; i < theArgs.length; i++) {
if (arr.includes(theArgs[i])) {
arr.splice(arr.indexOf(theArgs[i]), 1);
}
}
return arr;
};
The above fixes the code your way, but a better way of doing it would be using filter.
const removeFromArray = function (arr, ...theArgs) {
return arr.filter(ele => !theArgs.includes(ele))
}
I am writing it this way to purely maintain your function.
The problem is because you remove item from the array while being looping from that array.
Every time your for loop iterate the array, it will get a new array
e.g. (1,2,3,4,5 => 2,3,4,5), but the i value just keeping increasing by 1.
const removeFromArray = function (arr, ...theArgs) {
for (let i = 0; i < arr.length; i++) {
console.log(`arr:${arr}`,`item${arr[i]}`,`num${i}`)
console.log(arr[i])
if (theArgs.includes(arr[i])) {
arr.splice(i, 1);
}
}
return arr;
};
const testarray = [1,2,3,4,5]
console.log(removeFromArray(testarray,1,2,3))
I would suggest to use array as a second parameter.
var array1 = ['a','b','c'];
var elementsToRemove = ['a','b'];
const removeFromArray = function (array1, elementsToRemove) {
var filtered = array1.filter(function(value, index, array){
return elementsToRemove.includes(value);
});
return filtered;
}
console.log(removeFromArray(array1,elementsToRemove));

How to I take an array and put it into another array to make a multi-dimensional array in Javascript

I want to make an array, then push arrays onto the array as elements. How do I do that?
let array3 = [];
const array1 = [1,2];
const array2 = [3,4];
array3.push(array1);
console.log(array3);
// expected [[1,2]]
array3.push(array2);
console.log(array3);
// expected [[1,2],[3,4]]
This what I am trying to make work:
const _ = {
chunk: (array, chunkSize = 1) =>{
console.log(`Original Array: ${array}` );
let chunk = [];
let chunkArr = [];
while(array.length > 0)
{
while(chunk.length < chunkSize && array.length > 0)
{
chunk.push(array.shift());
}
console.log(`Chunk: ${chunk}`);
chunkArr.push(chunk);
console.log(`Chunk Array: ${chunkArr}` );
while(chunk.length > 0)
{
chunk.pop();
}
}
//console.log(`chunk array: ${chunkArr}` );
return chunkArr;
}
// end of _ object
};
const array = [1,2,3,4];
console.log(_.chunk(array, 2));
const array1 = [1,2,3,4,5,6,7,8];
const chunk = (arr, size = 2, sum = []) => {
if (arr.length <= size) {
return sum.concat([arr])
}
return chunk(arr.slice(size), size, sum.concat([arr.slice(0, size)]));
}
console.log(chunk(array1, 5))

How to check if two numbers are equal in javascript [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 3 years ago.
Let's say we have an array:
let arr = [10,10,5,11,5]
How could I check for all the numbers that are equal? ( basically duplicates )
What i thought of is a forEach and compare every number but that's not very optimal. A filter ? Maybe. Anyone has any good ideea that would be optimal?
You can use reduce to build down the values you need
let arr = [10, 10, 5, 11, 5];
let duplicates = getDuplicates(arr);
console.log(duplicates);
function getDuplicates(arr) {
let duplicates = arr.reduce((acc, item) => {
if(acc[item] !== undefined) {
acc[item] = true;
} else {
acc[item] = false;
}
return acc;
}, {});
return Object.keys(duplicates).filter(item => duplicates[item]);
}
You can use filter
let arr = [10,10,5,11,5];
const duplicates = array => array.filter((item, index) => array.some((i, idx) => i === item && idx < index));
console.log(duplicates(arr));
or reduce
let arr = [10,10,5,11,5];
const duplicates = array => array.reduce((results, item, index) => {
if (!results.some(i => i === item) && array.some((i, idx) => i === item && index !== idx)) {
results.push(item);
}
return results;
}, []);
console.log(duplicates(arr));
You can use a Set to remove the duplicates and then compare the lengths of the two arrays.
let arr1 = [10,10,5,11,5]
let arr2 = [10,11,5]
function hasDuplicates(arr) {
return arr.length != [...new Set(arr)].length
}
console.log(hasDuplicates(arr1))
console.log(hasDuplicates(arr2))
Really quick with every
let arr = [10,10,5,11,5]
//arr = [10,10,10,10]
if (arr.every( v => v === arr[0] )) {
console.log("yes")
} else {
console.log("no")
}
Or using Lodash
let arr = [10,10,5,11,5]
//arr = [10,10,10,10]
if (_.uniq(arr).length == 1) {
console.log("yes")
} else {
console.log("no")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

ES6 Array methods to remove / detect duplicate objects in an array

I am trying to add an object to an array if the array already does not have that object.
So I have an array as follows
[{id:1},{id:2},{id:3}]
I want to check if a id:1 exist or not if not then add if yes then show an error or log a message.
I am able to achieve this using a simple array as follows.
let result =[1,2,2,3,1,4,1,4,2,3].filter((el, i, a) => i === a.indexOf(el));
I cannot figure out how to achive the same with array of objects.
Thanks
You can use some to check for duplicates like:
// array with duplicate objects {id:1}
let arr = [{id:1},{id:1},{id:2}]
function duplicateFound(arr){
const ids = arr.map(x => x.id);
return ids.some((item, idx) => ids.indexOf(item) != idx);
}
console.log(duplicateFound(arr));
// array with not duplicates
arr = [{id:1},{id:2},{id:3}]
console.log(duplicateFound(arr));
You can use Array#filter, and check the length:
const arr = [{id:1},{id:2},{id:3}];
const el = { id: 1 };
const exists = arr.filter(({ id }) => id === el.id).length > 0;
console.log(exists);
Or you can use Array#find, which has a slight advantage over Array#filter, since it will stop as soon as an item was found.
const arr = [{id:1},{id:2},{id:3}];
const el = { id: 1 };
const exists = !!arr.find(({ id }) => id === el.id);
console.log(exists);
You can wrap your array with a proxy that has a set trap, to prevent the insertion of duplicates automatically:
const arr = [{id:1},{id:2},{id:3}];
const arrayChangeHandler = {
set: function(target, property, value, receiver) {
if(property === 'length') {
return true;
}
const exists = !!target.find(({ id }) => id === value.id);
if(exists) {
console.log(`Id: ${value.id} exists!`); // you can return false here, and it will throw an error
} else {
target.push(value);
}
return true;
}
};
const pArr = new Proxy(arr, arrayChangeHandler);
pArr.push({ id: 1 });
pArr.push({ id: 10 });
console.log(JSON.stringify(arr));
You could try inserting all values as keys to a new array then flip keys & vals
let arr = "abccba".split('');
let res = [];
arr.forEach((n) => {
res[n] = n;
});
console.log(Object.keys(res));
A concern might be that if your values are numbers then you might need to recast them eg.
res = res.map(n) => +n

JQuery remove duplicate from array where string contains same text

I have an array with X number of items. Each has variables separated by a pipe character. In a loop I can split on the pipe to get the second item; but how do I splice to remove the duplicate.
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803"
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803"
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
Results should be this.
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803"
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803"
Note that the duplicate 22622138 is a random number so the solution needs to work for any number in this location (it's always in the arr[1] position).
This is what I tried:
$.each(arr_transcript, function (i, e) {
if (e.length != 0) {
var arr = e.split("|")
var i = arr_transcript.indexOf(arr[1]);
if (i != -1) {
arr_transcript.splice(i, 1);
}
}
});
Here's a generic function:
function uniqBy(a, key) {
let seen = new Set();
return a.filter(item => {
let k = key(item);
return !seen.has(k) && seen.add(k);
});
};
var data = [
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803",
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803",
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
];
var result = uniqBy(data, item => item.split('|')[1]);
console.log(result)
See here for more info.
Create a map of the numbers you want to check against, and then filter based on that
var arr_transcript = [
"Sometext|22621086|address|333629dc87894a7ea7df5291fa6d1836|PC_E|1803",
"Sometext2|22622138|working|d3e70175ffe942568cd21f1cf96f4d63|PC_E|1803",
"Sometext3|22622138|working|851946e6325445da99c113951590f714|PC_E|1803"
];
var map = arr_transcript.map(function(text) {
return text.split('|')[1];
});
var filtered = arr_transcript.filter(function(item, index) {
return index === map.lastIndexOf( map[index] );
});
console.log(filtered)

Categories