String to array js [duplicate] - javascript

This question already has an answer here:
Split string into array of equal length strings
(1 answer)
Closed 2 years ago.
I want to convert a String '1234567' to Array
like this['123','456','7']
i have try this:
let str='1234'
let num=3;
let temp='';
let array=str.split('')
let newArr=[];
for(let i = 0;i<array.length;i++){
if((i+1)%num!==0){
temp+=array[i]
}else{
temp+=array[i]
newArr.push(temp)
temp='';
}
}
console.log(newArr)
but it miss the 4

When the loop finishes, temp may be non-empty without having been added to newArr. One way to handle this would be to check for this scenario after the loop and handle accordingly.
// after the for-loop
if (temp) {
newArr.push(temp)
}

Related

array.push() and splite in Array of arrays [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 6 days ago.
This post was edited and submitted for review 6 days ago.
I'm using arrayofArrays[0].push() inside a for loop in order to add an Object to the Array0 inside arrayofArrays.
Now I'd like that when Array0 has reached 2 element, the next element will be pushed to Array1, in order to achieve this situation:
var arrayofArrays = [[Obj0,Obj1],[Obj2,Obj3],[Obj4,Obj5], ...];
Sample code:
var arrayofArrays = [[]];
for(data in Data){
var Obj = {"field1":data[0], "field2":data[1], "field3":data[2] }
arrayofArrays[0].push(Obj); // need to pass to arrayofArrays[1] when arrayofArrays[0] has 2 Obj...
}
(I don't need to split an existing array, I'm adding Object to an array, and want them to split in sub-arrays while adding them)
Here is a functional programming approach to your question to unflatten an array:
const arr = Array.from(Array(6).keys()); // [0, 1, 2, 3...]
let t;
let arrOfArr = arr.map((v, idx) => {
if(idx % 2) {
return [t, v];
} else {
t = v;
return null;
}
}).filter(Boolean);
console.log({
arr,
arrOfArr,
});
Note: Array.from(Array(6).keys()) is just for demo. Replace this with any array of objects you like

How do i show values that are duplicate in an array from a textarea [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 2 years ago.
I have an array as such:
let newArray = $('#TA2').val().split('\n');
Where #TA2 is a textarea. The output from console.log is:
["542|519", "542|519", "540|500"]
I want to show only the values that are duplicate, so the output should be: ["542|519"]
How do i do this using js/jquery? everything i try won't work unfortunately and i'm in need of help..
The diffrence in this question related to others is that i want my array to be dynamic with textarea input hence the first variable newArray that gets the values from the textarea to create a new array. The end-goal is to add a <button>, when clicked on a array should be created from the textarea and must only show the duplicate values.
You can use reduce and for..in. Use reduce to create a object where keys will be 542|519 like this and it's value will be the number of occurrence. So if the value is more than 1 then it is a duplicate
let dups = ["542|519", "542|519", "540|500"].reduce((acc, curr) => {
if (acc[curr]) {
acc[curr] += 1
} else {
acc[curr] = 1
}
return acc;
}, {});
for (let keys in dups) {
if (dups[keys] > 1) {
console.log(keys)
}
}

Is there .count method in javascript like python? [duplicate]

This question already has answers here:
Idiomatically find the number of occurrences a given value has in an array
(11 answers)
How to count certain elements in array?
(27 answers)
Closed 2 years ago.
In Python, if we have a list,
array = [1,2,3,4,5]
If we say array.count(1), it will return the count of 1 in array.
Is there a method like this in javascript?
I think there isn't. But you can make one by using prototype.
let array = [1,2,3,4,5,1];
Array.prototype.count = function(value) {
let count = 0;
this.forEach(item => {
if (item === value) {
count++;
}
});
return count;
}
console.log(array.count(1));
console.log(array.count(2));

Find partial string in array [duplicate]

This question already has answers here:
How do you search an array for a substring match?
(15 answers)
Closed 3 years ago.
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"];
var n = fruits.includes("Mango");
Let's say you don't know whats inside the fruits array ?
How do you extract the string that contains mango.
The prefix string must be included in the result.
Can this be done without a for loop and parsing ?
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"];
var n = fruits.includes("Mango");
console.log(n)
You need to filter the array and check each string.
var fruits = ["CarPaint.InString.Banana", "CarPaint.InString.Orange", "CarPaint.InString.Apple", "CarPaint.InString.Mango"],
result = fruits.filter(string => string.includes("Mango"));
console.log(result);
How about the following?
fruits.filter(fruit => fruit.includes('Mango'))
// [ 'CarPaint.InString.Mango' ]

How to immutably insert into a sorted array? [duplicate]

This question already has answers here:
Efficient way to insert a number into a sorted array of numbers?
(18 answers)
Closed 3 years ago.
How do I immutably insert an element into a sorted array? (Let's assume an array of integers for simplicity)
The reason for this question: I'm writing a reducer for a React app, where the order of elements in my particular array is important.
The closest solution I've found is this one here, but it doesn't cover insertions into a sorted array.
Try this one.
let sortedArr = [1,2,5,9,12];
const newItem = 7;
for (let i = 0; i < sortedArr.length; i++) {
if (newItem <= sortedArr[i]) {
sortedArr = [...sortedArr.slice(0, i), newItem, ...sortedArr.slice(i)];
break;
}
}
console.log(sortedArr);

Categories

Resources