Find index of array starting at specific location - javascript

Say I have the following array:
const array = ['1', '2', '3', '1', '2', '3']
I want to use the following to find the index of '2'
let index = array.findIndex(c => c === '2');
The index would be 1 in this case, but I want to purposely start at index 2 so the result would be 4 instead of 1.
Any thoughts?
const array = ['1', '2', '3', '1', '2', '3'];
let index = array.findIndex(c => c === '2');
console.log(index);

You can use Array.indexOf() and set the fromIndex (2nd param) to 2:
const array = ['1', '2', '3', '1', '2', '3'];
const index = array.indexOf('2', 2);
console.log(index);
If you must use Array.findIndex() (to find an object for example), you can use the 2nd param passed to the callback (the index) to limit the search:
const array = ['1', '2', '3', '1', '2', '3'];
const index = array.findIndex((c, idx) => idx > 1 && c === '2');
console.log(index);

Related

Convert key-value array back into normal array with Object.fromEntries()

Let's suggest I have an array:
const arr = ['1', '2', '3', '4']
And Object.entries(arr) returns the following: [[0, '1'], [1, '2'], [2, '3'], [3, '4']].
How to convert it back to a normal array? That is:
['1', '2', '3', '4']
Because Object.fromEntries(Object.entries(arr)) returns {0: '1', 1: '2', 2: '3', 3: '4'} -- not what I expected.
UPD
Do not accept answers like Object.values(obj) because sometimes I need a normal key-value object from Object.fromEntries()
You could map
const arr = ['1', '2', '3', '4']
const entries = Object.entries(arr)
console.log(entries)
console.log(entries.map(item => item[1]))
// or
console.log(entries.map(([key,val]) => val))
Use map() to get the second index of each nested array:
const arr = ['1', '2', '3', '4'];
const rra = Object.entries(arr);
const original = rra.map(i => i[1]);
console.log(original);

Compare array with another array, matching all elements (TypeScript, Angular Pipe)

I have been wrapping my head around a filtering issue I have in an Angular Pipe.
A multiselect component contains a string array of elements, of which the selection acts as an AND operation. What I want to do is return all items matching at least all the items in the filter.
I have so far used some for this, which works great for OR, so I thought that every would do the same for AND, but in the parent filter it always returns all the items, meaning the condition is always true.
This is a simplified extract of my code
let filterItems: string[] = ['1', '2', '3', '4', '5', '6'];
let filterSelection: string[] = ['2', '3'];
let item1: string[] = [];
let item2: string[] = ['2'];
let item3: string[] = ['2', '3'];
let item4: string[] = ['2', '3', '5', '6'];
console.log(item1.every(x => filterSelection.includes(x)));
console.log(item2.every(x => filterSelection.includes(x)));
console.log(item3.every(x => filterSelection.includes(x)));
console.log(item3.every(x => filterSelection.includes(x)));
The expected result would be
Item1: false
Item2: false
Item3: true
Item4: true
Only when the AND conditions are met, the item should be returned. I am probably misinterepreting the use of every here, but have tried several things, such as switching the arrays around, using indexOf instead of includes, using some, negated some with filter, but none of them give the result I want.
You swaped your arrays for what you want.
let filterItems: string[] = ['1', '2', '3', '4', '5', '6'];
let filterSelection: string[] = ['2', '3'];
let item1: string[] = [];
let item2: string[] = ['2'];
let item3: string[] = ['2', '3'];
let item4: string[] = ['2', '3', '5', '6'];
console.log(filterSelection.every(x => item1.includes(x)));
console.log(filterSelection.every(x => item2.includes(x)));
console.log(filterSelection.every(x => item3.includes(x)));
console.log(filterSelection.every(x => item4.includes(x)));

Remove Item from Array using only word

I was wondering how to remove an item from an array only with the world, not array[0], etc.
let input = ['a', 'b', 'c'];
let output = input.filter(item => item !== 'b'); //["a", "c"]
You can use splice method for this and get element position with indexOf
This will remove only first finded element
let testArray = ['1','2','3','4'];
let blackWorld = '2'
if(testArray.includes(blackWorld)) testArray.splice(testArray.indexOf(blackWorld),1)
console.log(testArray) // [ '1', '3', '4' ]
Or use filter method, so it will remove all elements if they equal your value for 1 blackworld
let testArray = ['1','2','3','4','2'];
let blackWorld = "2"
let newArray = testArray.filter(item => item !== blackWorld)
console.log(newArray) // [ '1', '3', '4' ]
For array of blackworlds
let testArray = ['1','2','3','4'];
let blackWorlds = ['1','2']
let newArray = testArray.filter(item => !blackWorlds.includes(item))
console.log(newArray) // [ '3', '4' ]

Javascript insert element at nth index in array, insertion elements from another array [duplicate]

This question already has answers here:
How to insert an item into an array at a specific index (JavaScript)
(28 answers)
Closed 3 years ago.
I have 2 Javascript arrays:
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
['a', 'b', 'c']
I need to insert elements of second array into the first array every 4th or nth index of the first array, resulting in:
['a', '1', '2', '3', '4', 'b', '5', '6', '7', '8', 'c', '9', '10', '11', '12']
n needs to be a parameter, so I can move n to the 5th location, or 3rd location when needed.
Any solutions appreciated. ES6 ones would be great! Thank you in advance.
You can iterate through the smaller array using forEach use splice() to insert elements.
let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
let arr2 = ['a', 'b', 'c']
function insertArr(arr1,arr2,n){
arr1 = arr1.slice();
arr2.forEach((a,i) => {
arr1.splice(i*n+i,0,a);
})
return arr1;
}
console.log(insertArr(arr1,arr2,4))
Try this
b.forEach((itm, indx) => a.splice(Math.ceil(a.length/b.length)*indx, 0, itm));
Use a forEach with iterator as below:
let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
let arr2 = ['a', 'b', 'c'];
let index = 0;
arr2.forEach(function(v){
arr1.splice(index, 0, v);
index += 5;
});
console.log(arr1);
Now about the ES6, here is how I would write it:
let arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
let arr2 = ['a', 'b', 'c'];
let index = 0;
Array.from(arr2).forEach((v)=>{
arr1.splice(index, 0, v);
index += 5;
});
console.log(arr1);
Iterate the 2nd array with Array.flatMap(), take the respective sequence from the 1st array with Array.slice(), and combine it with the current element using spread. Use Array.concat() with slice to add leftover items if any.
const fn = (n, added, target) =>
added.flatMap((el, i) => [el, ...target.slice(n * i, n * (i + 1))])
.concat(target.slice(n * added.length))
const arr1 = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
const arr2 = ['a', 'b', 'c']
console.log(JSON.stringify(fn(3, arr2, arr1)));
console.log(JSON.stringify(fn(4, arr2, arr1)));
console.log(JSON.stringify(fn(5, arr2, arr1)));

I'm trying to create new array of array from one array [duplicate]

This question already has answers here:
Split array into chunks
(73 answers)
Closed 5 years ago.
I'm trying to create new array of array from one array,
How to make
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
become
var array = [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8'], ['9', '10']];
Use a simple loop with Array#splice method to update the same array.
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
size = 2;
// iterate upto the length(which is dynamic)
for (var i = 0; i < array.length; i++)
// remove the 2 elements and insert as an array element
// at the same index
array.splice(i, 0, array.splice(i, size));
console.log(array);
In case you want to generate a new array then use Array#slice method.
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
size = 2,
res = [];
// iterate over the array where increment index by the size
for (var i = 0; i < array.length; i += size)
// push the subarray
res.push(array.slice(i, i + size));
console.log(res);
An ES6 alternative with Array.from method:
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'],
size = 2;
var res = Array.from({
// create an array of size based on the chunk size
length: Math.ceil(array.length / size)
// iterate and generate element by the index
}, (_, i) => array.slice(i * size, i * size + size))
console.log(res);
Try the following:
var array = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var newArray = [];
var i,j,chunk = 2;
for (i=0,j=array.length; i<j; i+=chunk) {
newArray.push(array.slice(i,i+chunk));
}
console.log(newArray);

Categories

Resources