Check if array2 is partially ordered as array1 in JavaScript

Is there a more efficient way to achieve these conditions in JavaScript using vanilla or lodash?

const array1 = [1, 2]
const array2 = [1, 2, 3, 4] //true
const array2 = [1, 3, 2, 4] //true
const array2 = [4, 3, 2, 1] //false
const array2 = [2, 3, 1, 4] //false

I have attempted the following approach.

const _ = require('lodash');

const array1 = [1, 2];
const array2 = [1, 2, 3, 4];

const trimmed = array2.filter((n) => combinations.indexOf(n) > -1);
const isEqual = _.isEqualWith(array1, trimmed);
console.log(isEqual);

If you have a cleaner and more flexible solution for this problem, please share.

Answer №1

To verify whether each element in arr2 is not present in arr1 or is at the current index i in arr1, you can utilize Array.every():

const fn = (arr1, arr2) => {
  let i = 0
  
  return arr2.every(v => !arr1.includes(v) || v === arr1[i++])
}

console.log(fn([1, 2], [1, 2, 3, 4]))
console.log(fn([1, 2], [1, 3, 2, 4]))
console.log(fn([1, 2], [4, 3, 2, 1]))
console.log(fn([1, 2], [2, 3, 1, 4]))

Another approach involves shallow cloning the first array with destructuring and rest syntax, then using Array.shift() to examine the current first element of arr1:

const fn = ([...arr1], arr2) => arr2.every(v => !arr1.includes(v) || v === arr1.shift())

console.log(fn([1, 2], [1, 2, 3, 4]))
console.log(fn([1, 2], [1, 3, 2, 4]))
console.log(fn([1, 2], [4, 3, 2, 1]))
console.log(fn([1, 2], [2, 3, 1, 4]))


Using lodash, you can find the intersection of arr2 and arr1 to compare if they are equal (same elements in the same order):

const fn = (arr1, arr2) => _.isEqual(
  _.intersection(arr2, arr1),
  arr1
)

console.log(fn([1, 2], [1, 2, 3, 4]))
console.log(fn([1, 2], [1, 3, 2, 4]))
console.log(fn([1, 2], [4, 3, 2, 1]))
console.log(fn([1, 2], [2, 3, 1, 4]))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" integrity="sha512-WFN04846sdKMIP5LKNphMaWzU7YpMyCU245etK3g/2ARYbPK9Ub18eG+ljU96qKRCWh+quCY7yefSmlkQw1ANQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Answer №2

If all elements in array1 are guaranteed to be present in array2, you can implement the two pointer approach.

Here is an example of how you can do it:

/** Function to determine if arr2 is partially ordered like arr1 */
function isPartiallyOrdered(arr1, arr2) {
  let i = 0;
  for (let j = 0; j < arr2.length && i < arr1.length; j++) {
    if (arr1[i] === arr2[j]) i++;
  }

  return i === arr1.length;
}

console.log(isPartiallyOrdered([1, 2], [1, 2, 3, 4])); // true
console.log(isPartiallyOrdered([1, 2], [1, 3, 2, 4])); // true
console.log(isPartiallyOrdered([1, 2], [4, 3, 2, 1])); // false
console.log(isPartiallyOrdered([1, 2], [4, 3, 2, 1])); // false

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can VueJS lifecycle hooks be outsourced?

Is it possible to organize lifecycle hooks (like created / mounted) in a separate file for better simplicity and cleanliness? MyGreatView.vue import created from 'created.js' export default { created, // created() { console.log('vue Cre ...

Tips on combining multiple HTML tags within a single div element

After extracting a value from an XML document using Javascript, I encountered a problem while attempting to generate multiple image tags based on that value. Despite my attempt with a for loop, only one image was being displayed. for(i=0; i<red; i++){ ...

Having trouble executing a jQuery function within AJAX-generated code

I may not be very experienced in JavaScript programming, but I am learning and trying my best to improve. Please excuse any errors I make along the way. Currently, I am attempting to use Ajax (not jQuery ajax) to save customer details, which then returns ...

Avoiding Multiple Clicks on Anchor Tags in AngularJS

After implementing the sharing functionality, I have noticed that it works fine but there is a repeating issue with the user list. Every time the 'a' tag is clicked multiple times, the user list gets repeated. Can someone guide me on how to resol ...

Received undefined instead of a Promise or value from the function in Nodemailer

I'm currently exploring cloud functions and trying to implement email notifications for document creation triggers in Firestore. I found a helpful tutorial that guided me through the process, but I encountered an error while analyzing the cloud functi ...

What is the process for calculating and determining the exact area the div should be released?

I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with ...

Organize my JavaScript code by implementing a function

I have repetitive javascript code that I would like to refactor into a function. Is there a way to streamline this process and make the code more efficient? The two functions I want to consolidate are: bright() $(VARIABLE).find('.info').fadeTo ...

Clicking on an Angular routerLink that points to the current route does not function unless the page is re

Currently, I am working on an E-commerce project. In the shop page, when a user clicks on the "View More" button for a product, I redirect them to the product details page with the specific product id. <a [routerLink]="['/product-details' ...

Combine several pages from PDF files into a single document

I am currently working on developing a small electron application that combines multiple PDF files or pages into one larger page to help save paper when printing several CAD drawings. Essentially, I am looking for a cross-platform solution similar to the ...

Organizing a drop down list in alphabetical order with Angular.js is not supported

I have encountered an issue with ordering the drop down list alphabetically using Angular.js. Below is the code I am using: <div class="input-group bmargindiv1 col-md-12"> <span class="input-group-addon ndrftextwidth text-right" style="width:180p ...

Can someone explain the inner workings of the Typescript property decorator?

I was recently exploring Typescript property decorators, and I encountered some unexpected behavior in the following code: function dec(hasRole: boolean) { return function (target: any, propertyName: string) { let val = target[propertyName]; ...

What is the best way to update the value of a specific key in discord.js?

As I struggle to explain properly due to my limited English proficiency, I am reiterating my question. In my config.json file, there is a key named "status" with a corresponding value of "online". I am attempting to change this value but haven't been ...

Tips for executing jsfiddle code within Joomla 3.2

I'm having trouble executing this code on my Joomla website. I have Joomla 3.2 installed with the JCK Editor, but the HTML tags are not functioning correctly. Can someone please assist me in running the following code: $("#text10").keyup(functio ...

Can we modify the styling of elements in Angular based on an object property?

I have a class named Task with the following properties: export class Task { name: string; state: number; } Within my component.ts file, I have an array of objects consisting of instances of the Task class (tasks). When displaying them in the tem ...

How can I adhere to Angular 2's naming convention for Input and Output as suggested by the styleguide?

Working with inputs and outputs while following Angular 2's styleguide naming convention Initially, my directive was defined like this: ... inputs: [ 'onOutside' ] ... export class ClickOutsideDirective { @Output() onOutside: EventEmitter ...

Is there a constraint on JSON data?

Is there a limit to the amount of data that JSON with AJAX can handle in outgoing and returning parameters? I am trying to send and receive a file with 10,000 lines as a string from the server. How can I accomplish this task? Can a single parameter manage ...

Does the Node Schedule library create new processes by spawning or forking them?

Is the node-schedule npm module responsible for spawning/forking a new process, or do we need to handle it ourselves? var cron = require('node-schedule'); var cronExpress="0 * * * *"; cron.scheduleJob(cronExpress, () => { //logger.info(" ...

Material-UI: The Mystery of Missing CSS Properties

Struggling to apply a CSS class to an element from Material-UI: bw:hover { -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */ filter: grayscale(100%); } Tried using makeStyles: import { makeStyles } from '@material-ui/core/styles' ...

ReactJS integration issue with Material Design Lite (import/require problem)

I am currently integrating Google's Material Design Lite with ReactJS. Specifically, I am utilizing the Spinner Loading and Text Field components from the MDL library. However, I am encountering an issue when switching routes using React Router. The ...

What are the steps for creating an animated visualization of the peak chart?

As a newcomer to CSS and Javascript, I am currently struggling with animating a peak (bar) chart that I came across on codepen. If anyone can provide assistance or guidance, it would be greatly appreciated! The chart can be found here: http://codepen.io/An ...