Search nested array in lodash/es6 - javascript

Looking to search a value in an array of array and returning index. Most of the answers are array of objects. So I am looking to search for eg 22 and get 2 as the index where the value was found
Here is the code pen
https://codesandbox.io/s/lodash-playground-array-pzzhe
const arr = [["a","b"],["f","r"],["r",22,"t"]];
console.log("arr", arr);

You could take plain Javascript with Array#findIndex with Array#includes.
var array = [["a", "b"], ["f", "r"], ["r", 22, "t"]],
value = 22,
index = array.findIndex(a => a.includes(value));
console.log(index);

Option 1 Use findIndex
const arr = [["a","b"],["f","r"],["r",22,"t"]];
console.log(arr.findIndex(a => a.includes(22)));
Option 2: Use functions indexOf and includes:
const arr = [["a","b"],["f","r"],["r",22,"t"]];
// find element
const element = arr.find(a => a.includes(22));
// find element index
const currentIndex = arr.indexOf(element)
console.log(currentIndex);

indexOfFlat = (val, array) => array.findIndex(_arr => _arr.includes(val));
const arr = [["a","b"],["f","r"],["r",22,"t"]];
console.log("arr", arr);
console.log("index", indexOfFlat(22, arr))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.min.js"></script>

In case you would actually need the sub-array in which the value was found, you could also use Array.find and its index and get both:
const arr = [["a","b"],["f","r"],["r",22,"t"]];
let index, subArr = arr.find((x,i) => x.includes(22) && ~(index=i))
console.log('sub-array: ', subArr)
console.log('index: ', index)

Related

Find nested array by value

I've searched high and low for an answer to this, but nothing.
I have a nested array and want to find it by exact value but can't seem to get it to work:
let rowLetters = ["A","B","C",["D","E"],"F"];
for(n=0;n<rowLetters.length;n++){
if(rowLetters[n] === ["D","E"]){
console.log("Found");
}
console.log(rowLetters[n]);
}
Console Output:
"A"
"B"
"C"
["D","E"] // <-- There it is..
"F"
What am I doing wrong?
You need to check
if item is an array,
if item has the same length as the wanted value array and
if the values of the arrays are equal.
let rowLetters = ["A", "B", "C", ["D", "E"], "F"],
search = ["D", "E"];
for (const item of rowLetters) {
if (Array.isArray(item) && item.length === search.length && search.every((v, i) => item[i] === v)) {
console.log(item);
}
}
You can use filter with JSON.stringify()
let data = ["A", "B", "C", ["D", "E"], "F"];
let search = data.filter(ele => JSON.stringify(ele) == JSON.stringify(["D", "E"]));
if (search.length > 0) {
console.log("found")
}
Are you looking for something like find() mixed with Array.isArray()?
let rowLetters = ["A","B","C",["D","E"],"F"];
console.log(rowLetters.find(i => Array.isArray(i)))
You cannot compare an array to an array because you are comparing by a reference and not a value. You can however cast the value to a json string and compare, however, this requires exact order in both arrays.
let rowLetters = ["A","B","C",["D","E"],"F"];
for(let i of rowLetters){
if(JSON.stringify(i) === JSON.stringify(["D","E"])) {
console.log("Found");
}
}
You can use .find and JSON.stringify:
let rowLetters = ["A","B","C",["D","E"],"F"];
let arrayToFind = JSON.stringify(["D","E"])
let nestedArray = rowLetters.find( arr => JSON.stringify(arr) === arrayToFind );
console.log(nestedArray);
A better way to check if two arrays are equal would be using .every and .includes as follows:
let rowLetters = ["A","B","C",["D","E"],"F"];
const arraysAreEqual = (arr1, arr2) => {
if(arr1.length != arr2.length) return false;
return arr1.every( e => arr2.includes(e) );
}
const arrayToFind = ["D","E"];
let nestedArray = rowLetters.find( arr => arraysAreEqual(arr, arrayToFind) );
console.log(nestedArray);

Find indices of all duplicate records in js

Suppose I have an array as below:
Arr1 = [12,30,30,60,11,12,30]
I need to find index of elements which are repeated in array e.g.
ans: 0,1,2,5,6
I've tried this code but it is considering just single element to check duplicates.
First get all the duplicates using filter() and then using reduce() get he indexes of only those elements of array which are in dups
const arr = [12,30,30,60,11,12,30];
const dups = arr.filter(x => arr.indexOf(x) !== arr.lastIndexOf(x));
const res = arr.reduce((ac, a, i) => {
if(dups.includes(a)){
ac.push(i)
}
return ac;
}, []);
console.log(res)
The time complexity of above algorithm is O(n^2). If you want O(n) you can use below way
const arr = [12,30,30,60,11,12,30];
const dups = arr.reduce((ac, a) => (ac[a] = (ac[a] || 0) + 1, ac), {})
const res = arr.reduce((ac, a, i) => {
if(dups[a] !== 1){
ac.push(i)
}
return ac;
}, []);
console.log(res)
You could use simple indexOf and the loop to get the duplicate indexes.
let arr = [12,30,30,60,11,12,30]
let duplicate = new Set();
for(let i = 0; i < arr.length; i++){
let index = arr.indexOf(arr[i], i + 1);
if(index != -1) {
duplicate.add(i);
duplicate.add(index);
}
}
console.log(Array.from(duplicate).sort().toString());
A slightly different approach with an object as closure for seen items which holds an array of index and the first array, in which later comes the index and a necessary flattening of the values.
This answer is based on the question how is it possible to insert a value into an already mapped value.
This is only possible by using an object reference which is saved at the moment where a value appears and which is not seen before.
Example of unfinished result
[
[0],
[1],
2,
[],
[],
5,
6
]
The final Array#flat removes the covering array and shows only the index, or nothing, if the array remains empty.
[0, 1, 2, 5, 6]
var array = [12, 30, 30, 60, 11, 12, 30],
indices = array
.map((o => (v, i) => {
if (o[v]) { // if is duplicate
o[v][1][0] = o[v][0]; // take the first index as well
return i; // return index
}
o[v] = [i, []]; // save index
return o[v][1]; // return empty array
})({}))
.flat() // remove [] and move values out of array
console.log(indices);
You could use Array#reduce method
loop the array with reduce.At the time find the index of argument
And check the arguments exist more than one in the array using Array#filter
Finaly push the index value to new accumulator array.If the index value already exist in accumalator.Then pass the currentIndex curInd of the array to accumulator
const arr = [12, 30, 30, 60, 11, 12, 30];
let res = arr.reduce((acc, b, curInd) => {
let ind = arr.indexOf(b);
if (arr.filter(k => k == b).length > 1) {
if (acc.indexOf(ind) > -1) {
acc.push(curInd)
} else {
acc.push(ind);
}
}
return acc;
}, []);
console.log(res)
Below code will be easiest way to find indexes of duplicate elements
var dupIndex = [];
$.each(Arr1, function(index, value){
if(Arr1.filter(a => a == value).length > 1){ dupIndex.push(index); }
});
This should work for you

Remove out nested array based on another array

I have this nested array
let arr = [['first', 'second'], ['third', 'fourth'], ['second', 'third']]
now I want to filter/remove based on exactly this array.
let filter = ['first', 'second']
and now my expected output should be:
[['third', 'fourth'], ['second', 'third']]
I only have this piece of code:
arr.filter(str => str.indexOf('second') === -1)
Which doesn't give the expected output, it also removed ['second', 'third'] because it filters whatever element that contains 'second'.. so they must be a better way or an improvement to the code.
If you care about ordering and need exact matches, you can write a simple arrays equal method and then filter out any equal arrays:
const arrEq = (a, b) => a.length === b.length && a.every((e, i) => b[i] === e);
const arr = [['first', 'second'], ['third', 'fourth'], ['second', 'third']];
const filter = ['first', 'second'];
console.log(arr.filter(e => !arrEq(e, filter)));
If you want the same elements but order doesn't matter:
const arrItemsEq = (a, b, cmp) => {
if (a.length !== b.length) {
return false;
}
a = a.slice().sort(cmp);
b = b.slice().sort(cmp);
return a.every((e, i) => e === b[i]);
};
const arr = [["a", "b"], ["b", "c"]];
const filter = ["b", "a"];
const strCmp = (x, y) => x.localeCompare(y);
console.log(arr.filter(e => !arrItemsEq(e, filter, strCmp)));
If you want to filter out arr elements if they don't include at least one of each filter element:
const arr = [["a", "b"], ["b", "c"]];
const filter = ["b", "a"];
console.log(arr.filter(x => !filter.every(y => x.includes(y))));
You need to test two arrays for equality. [There are many ways to do it] but once you pick one, you can simply remove any array that is equal to another. To avoid reimplementing the wheel, I'll use the LoDash _.isEqual for demonstration purposes:
let arr = [['first', 'second'], ['third', 'fourth']]
let filter = ['first', 'second']
let result = arr.filter(item => !_.isEqual(filter, item));
console.log(result);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
The equality function can be swapped to any implementation that satisfies you. A very simple one is simply:
function isEqual(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
but it's not guaranteed to be correct (e.g, isEqual([1, 2], ["1,2"]) //true) and it's going to be slow with large inputs. But it might still work, depending on circumstances.
You can use filter to check if the element doesn't include every string of the filter array.
let arr = [['first', 'second'], ['third', 'fourth'], ['second', 'third']]
let filterout = ['first', 'second']
let arr2 = arr.filter(x => ! filterout.every(y => x.includes(y)))
console.log(arr2)
But by using filter it basically creates a new array with fewer elements. Which is good enough for a small array.
If if the goal is to directly change the original array, then those elements can be spliced from that array.
let arr = [ ['first', 'second'], ['third', 'fourth'], ['second', 'third'], ['second', 'first'] ]
let filterout = ['first', 'second']
// getting the indexes of the element that need to be removed
let idxArr = []
arr.forEach( (x, idx) => { if(x.every(y => filterout.includes(y))) idxArr.push(idx)})
// removing the elements from the array
idxArr.sort((i,j)=>j-i).forEach(idx => {arr.splice(idx, 1)})
console.log(arr)

Find elements in an array not contained in another array of objects

I have an array arr1 = [1,2,3,4,5]
There is another array of objects arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
I am looking for find elements in arr1 which are not in arr2. The expected output is [1,3,5]
I tried the following but it doesn't work.
const arr = arr1.filter(i => arr2.includes(i.id));
Can you please help?
A solution with O(arr2.length) + O(arr1.length) complexity in Vanilla JS
var arr1= [1,2,3,4,5];
var arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}];
var tmp = arr2.reduce(function (acc, obj) {
acc[obj['id']] = true;
return acc;
}, {});
var result = arr1.filter(function(nr) {
return !tmp.hasOwnProperty(nr);
})
arr2 is an array of objects, so arr2.includes(i.id) doesn't work because i (an item from arr1) is a number, which doesn't have an id property, and because arr2 is an array of objects.
Turn arr2's ids into a Set first, then check whether the set contains the item being iterated over:
const arr1 = [1,2,3,4,5];
const arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}];
const ids = new Set(arr2.map(({ id }) => id));
const filtered = arr1.filter(num => !ids.has(num));
console.log(filtered);
You can try with Array.prototype.some():
The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
const arr1 = [1,2,3,4,5]
const arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
const arr = arr1.filter(i => !arr2.some(j => j.id == i));
console.log(arr);
We can use the filter method like below to check the condition required
var arr1 = [1, 2, 3, 4, 5]
var arr2 = [{ 'id': 2, 'name': 'A' }, { 'id': 4, 'name': 'B' }]
var ids = [];
arr2.forEach(element => {
ids.push(element['id'])
});
var result = arr1.filter(s => ids.indexOf(s) < 0)
console.log(result)
let arr1= [1,2,3,4,5];
let arr2 = [{'id':2, 'name':'A'},{'id':4, 'name':'B'}]
let arr2Ids=arr2.map(item=>item.id);
let result=arr1.filter(n => !arr2Ids.includes(n));
You can use find on arr2 instead of includes since arr2 is composed of object
const arr = arr1.filter(i => !arr2.find(e => e.id===i));

split an array into two based on a index in javascript

I have an array with a list of objects. I want to split this array at one particular index, say 4 (this in real is a variable). I want to store the second part of the split array into another array. Might be simple, but I am unable to think of a nice way to do this.
Use slice, as such:
var ar = [1,2,3,4,5,6];
var p1 = ar.slice(0,4);
var p2 = ar.slice(4);
You can use Array#splice to chop all elements after a specified index off the end of the array and return them:
x = ["a", "b", "c", "d", "e", "f", "g"];
y = x.splice(3);
console.log(x); // ["a", "b", "c"]
console.log(y); // ["d", "e", "f", "g"]
use slice:
var bigOne = [0,1,2,3,4,5,6];
var splittedOne = bigOne.slice(3 /*your Index*/);
I would recommend to use slice() like below
ar.slice(startIndex,length);
or
ar.slice(startIndex);
var ar = ["a","b","c","d","e","f","g"];
var p1 = ar.slice(0,3);
var p2 = ar.slice(3);
console.log(p1);
console.log(p2);
const splitAt = (i, arr) => {
const clonedArray = [...arr];
return [clonedArray.splice(0, i), clonedArray];
}
const [left, right] = splitAt(1, [1,2,3,4])
console.log(left) // [1]
console.log(right) // [2,3,4]
const [left1, right1] = splitAt(-1, [1,2,3,4])
console.log(left1) // []
console.log(right1) // [1,2,3,4]
const [left2, right2] = splitAt(5, [1,2,3,4])
console.log(left1) // [1,2,3,4]
console.log(right1) // []
Some benefits compared to other solutions:
You can get the result with a one liner
When split index is underflow or overflow, the result is still correct. slice will not behave correctly.
It does not mutate the original array. Some splice based solutions did.
There is only 1 splice operation, rather than 2 slice operations. But you need to benchmark to see if there is actual performance difference.
You can also use underscore/lodash wrapper:
var ar = [1,2,3,4,5,6];
var p1 = _.first(ar, 4);
var p2 = _.rest(ar, 4);
Simple one function from lodash:
const mainArr = [1,2,3,4,5,6,7]
const [arr1, arr2] = _.chunk(mainArr, _.round(mainArr.length / 2));
const splitArrayByIndex = (arr, index) => {
if (index > 0 && index < arr.length) {
return [arr.slice(0, index), arr.slice(-1 * (arr.length - index))]
}
}
const input = ['a', 'x', 'c', 'r']
const output = splitArrayByIndex(input, 2)
console.log({ input, output })

Categories

Resources